流的关闭
程序员文章站
2022-04-09 17:29:02
...
import java.io.Closeable;
import java.io.IOException;
/**
* 工具类关闭流
* 可变参数:... 只能形参最后一个位置,处理方式与数组一致
*/
public class FileUtil01 {
public static void close(Closeable ...io){
for(Closeable temp:io){
if(null!=temp){
try {
temp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//使用泛型
public static <T extends Closeable> void closeAll(T...io){
for(Closeable temp:io){
if(null!=temp){
try {
temp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
jdk1.7新特性:try-with-resource
import java.io.*;
/**
* 转换流:字节转为字符
* 1、输出流OutputStreamWriter 编码
* 2、输入流InputStreamReader 解码
* try-with-resource jdk1.7新特性
*/
public class Demo05 {
public static void main(String[] args) throws IOException {
//文件的解码
try(
BufferedReader reader=new BufferedReader(
new InputStreamReader(
new FileInputStream(new File("D:/EnumMap12.java")),"UTF-8"));//文件以UTF-8格式解码
//文件的编码
BufferedWriter writer=new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(new File("D:/EnumMap13.java")),"GBK"
)//将文件以GBK格式编码
);) {
String info = null;
while (null != (info = reader.readLine())) {
writer.write(info + "\n");
System.out.println(info);
}
}
}
}