|
| 1 | +--- |
| 2 | +title: Java 字符流 |
| 3 | +date: 2015/05/19 |
| 4 | +categories: |
| 5 | +- javase |
| 6 | +tags: |
| 7 | +- javase |
| 8 | +- basics |
| 9 | +- io |
| 10 | +--- |
| 11 | + |
| 12 | +# Java 字符流 |
| 13 | + |
| 14 | +## 概念 |
| 15 | + |
| 16 | +Java 程序中,一个字符等于两个字节。 |
| 17 | + |
| 18 | +`Reader` 和 `Writer` 两个就是专门用于操作字符流的类。 |
| 19 | + |
| 20 | +`Writer` 是一个字符流的抽象类。 |
| 21 | + |
| 22 | +`Reader` 是读取字符流的抽象类。 |
| 23 | + |
| 24 | +## 文件字符流 |
| 25 | + |
| 26 | +`FileWriter` 示例 |
| 27 | + |
| 28 | +```java |
| 29 | +public class FileWriterDemo { |
| 30 | + |
| 31 | + public static void main(String args[]) throws Exception { // 异常抛出,不处理 |
| 32 | + // 第1步、使用File类找到一个文件 |
| 33 | + File f = new File("d:" + File.separator + "test.txt"); // 声明File对象 |
| 34 | + |
| 35 | + // 第2步、通过子类实例化父类对象 |
| 36 | + Writer out = new FileWriter(f); |
| 37 | + // Writer out = new FileWriter(f, true); // 追加内容方式 |
| 38 | + |
| 39 | + // 第3步、进行写操作 |
| 40 | + String str = "Hello World!!!\r\n"; |
| 41 | + out.write(str); // 将内容输出 |
| 42 | + |
| 43 | + // 第4步、关闭输出流 |
| 44 | + out.close(); |
| 45 | + } |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +`FileReader` 示例 |
| 50 | + |
| 51 | +```java |
| 52 | +public class FileReaderDemo { |
| 53 | + |
| 54 | + // 将所有内容直接读取到数组中 |
| 55 | + public static int read1(Reader input, char[] c) throws IOException { |
| 56 | + int len = input.read(c); // 读取内容 |
| 57 | + return len; |
| 58 | + } |
| 59 | + |
| 60 | + // 每次读取一个字符,直到遇到字符值为-1,表示读文件结束 |
| 61 | + public static int read2(Reader input, char[] c) throws IOException { |
| 62 | + int temp = 0; // 接收每一个内容 |
| 63 | + int len = 0; // 读取内容 |
| 64 | + while ((temp = input.read()) != -1) { |
| 65 | + // 如果不是-1就表示还有内容,可以继续读取 |
| 66 | + c[len] = (char) temp; |
| 67 | + len++; |
| 68 | + } |
| 69 | + return len; |
| 70 | + } |
| 71 | + |
| 72 | + public static void main(String args[]) throws Exception { |
| 73 | + // 第1步、使用File类找到一个文件 |
| 74 | + File f = new File("d:" + File.separator + "test.txt"); |
| 75 | + |
| 76 | + // 第2步、通过子类实例化父类对象 |
| 77 | + Reader input = new FileReader(f); |
| 78 | + |
| 79 | + // 第3步、进行读操作 |
| 80 | + char c[] = new char[1024]; |
| 81 | + // int len = read1(input, c); |
| 82 | + int len = read2(input, c); |
| 83 | + |
| 84 | + // 第4步、关闭输出流 |
| 85 | + input.close(); |
| 86 | + System.out.println("内容为:" + new String(c, 0, len)); // 把字符数组变为字符串输出 |
| 87 | + } |
| 88 | +} |
| 89 | +``` |
0 commit comments