一、自己写一个工具类关闭
可变参数:...三个点,只能放在形参的最后一个位置。表示可以传递任意个参数,处理方式同数组。
程序
public static void close(Closeable... io) {
for (Closeable temp : io) {
if (temp != null) {
try {
temp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static <T extends Closeable> void closeAll(T... io) {
for (Closeable temp : io) {
if (temp != null) {
try {
temp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
<br />
二、1.7新增方法,try-with-resource
程序
public static void read(String srcPath) {
File src = new File(srcPath);
try (
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(src)));
)
{
Object o1 = ois.readObject();
Object o2 = ois.readObject();
if (o1 instanceof Employee) {
Employee e1 = (Employee) o1;
System.out.println(e1.getSalary());
System.out.println(e1.getName());
}
if (o2 instanceof Employee) {
Employee e2 = (Employee) o2;
System.out.println(e2.getSalary());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
网友评论