转换流

  • 初始化变量

    1
    private static final String FILENAME = "E:" + File.separator + "hello.txt";

字节输出流转换为字符输出流

1
2
3
4
5
6
7
8
9
10
private static void testWriter() {
File file = new File(FILENAME);
try {
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("Today is sunday.");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

字节输入流转换为字符输入流

1
2
3
4
5
6
7
8
9
10
11
12
13
private static void testReader() {
File file = new File(FILENAME);
try {
Reader reader = new InputStreamReader(new FileInputStream(file));
char[] chars = new char[100];
int length = reader.read(chars);
reader.close();
System.out.println("读取长度:" + length);
System.out.println("读取内容:" + new String(chars));
} catch (IOException e) {
e.printStackTrace();
}
}