字符流
当使用字节流读取文本文件时,可能会有一个小问题。
就是遇到中文字符时,可能不会显示完整的字符,那是因为==一个中文字符可能占用多个字节存储==。
所以Java提供一些字符流类,以字符为单位读写数据,专门用于处理文本文件。
字符输入流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| import com.sun.org.apache.xpath.internal.operations.String;
import java.io.File; import java.io.FileReader; import java.io.IOException;
public class ReaderExer { public static void main(String[] args) throws IOException { exer01(); exer02(); }
private static void exer01() throws IOException { FileReader filereader = new FileReader(new File("a.txt")); int b; while((b = filereader.read()) != -1){ System.out.print((char) b); } filereader.close(); }
private static void exer02() throws IOException { FileReader filereader = new FileReader(new File("a.txt")); char[] buff = new char[2]; int i; while((i = filereader.read(buff)) != -1){ System.out.print(buff); } filereader.close(); } }
|
字符输出流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| import com.sun.org.apache.xpath.internal.operations.String;
import java.io.File; import java.io.FileReader; import java.io.IOException;
public class ReaderExer { public static void main(String[] args) throws IOException { exer01(); exer02(); }
private static void exer01() throws IOException { FileReader filereader = new FileReader(new File("a.txt")); int b; while((b = filereader.read()) != -1){ System.out.print((char) b); } filereader.close(); }
private static void exer02() throws IOException { FileReader filereader = new FileReader(new File("a.txt")); char[] buff = new char[2]; int i; while((i = filereader.read(buff)) != -1){ System.out.print(buff); } filereader.close(); } }
|