字节流以字节为单位输入输出,字节流类名含有stream,字符流以字符为单位输入输出,字节流
类名含有reader或writer.为了通用性,java中字符是16位的unicode字符,所以8位的字节流必
须和16位的字符流进行转换。字节流到字符流的转换使用InputStreamReader类:
public InputStreamReader(InputStream in);
public InputStreamReader(InputStream in,String encoding);
public OuputStreamWriter(OnputStream in);
public OnputStreamWriter(OnputStream in,String encoding);
Reader和Writer类允许用户在程序中无缝的支持国际字符集,如果要读区的文件是别国语言,
要使用字符流。
下面是一个利用BufferReader,BufferWriter读些文件的例子:
1 import java.io.*;
2
3 public class TestBufferedStreams {
4 public static void main(String[] args) {
5 try {
6 FileReader input = new FileReader(args[0]);
7 BufferedReader bufInput = new BufferedReader(input);
8 FileWriter output = new FileWriter(args[1]);
9 BufferedWriter bufOutput = new BufferedWriter(output);
10 String line;
11
12 // read the first line
13 line = bufInput.readLine();
14
15 while ( line != null ) {
16 // write the line out to the output file
17 bufOutput.write(line, 0, line.length());
18 bufOutput.newLine();
19
20 // read the next line
21 line = bufInput.readLine();
22 }
23
24 bufInput.close();
25 bufOutput.close();
26 } catch (IOException e) {
27 e.printStackTrace();
28 }
29 }
30 }