要读取格式化的数据,可以使用DataInputStream。
1public class FormattedMemoryInput {2 public static void main(String[] args) throws IOException {
3 try {
4 DataInputStream dataIns = new DataInputStream(
5 new ByteArrayInputStream(BufferedInutFile.readFile("f:/FormattedMemoryInput.java").getBytes()));
6 while (true){
7 System.out.print((char) dataIns.readByte());
8 }
9 } catch (EOFException e) {
10 System.err.println("End of stream");
11 }
12 }
13}
上面程序会在控制台输出当前类本身的所有代码,并且会抛出一个EOFException异常。抛出异常的原因是已经到留的结尾了还在读数据。这里可以使用available()做判断还有多少可以的字符。
1package com.herp.pattern.strategy;2
3import java.io.ByteArrayInputStream;
4import java.io.DataInputStream;
5import java.io.IOException;
6
7public class FormattedMemoryInput {
8 public static void main(String[] args) throws IOException {
9 DataInputStream dataIns = new DataInputStream(
10 new ByteArrayInputStream(BufferedInutFile.readFile("FormattedMemoryInput.java").getBytes()));
11 while (true){
12 System.out.println((char) dataIns.readByte());
13 }
14 }
15}
基本的文件输出
FileWriter对象可以向文件写入数据。首先创建一个FileWriter和指定的文件关联,然后使用BufferedWriter将其包装提供缓冲功能,为了提供格式化机制,它又被装饰成为PrintWriter。
1public class BasicFileOutput {2 static String file = "BasicFileOutput.out";
3
4 public static void main(String[] args) throws IOException {
5 BufferedReader in = new BufferedReader(new StringReader(BufferedInutFile.readFile("f:/BasicFileOutput.java")));
6 PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
7
8 int lineCount = 1;
9 String s;
10 while ((s = in.readLine()) != null){
11 out.println(lineCount ++ + ": " + s);
12 }
13 out.close();
14 in.close();
15 }
16}
下面是我们写出的BasicFileOutput.out文件,可以看到我们通过代码字节加上了行号
11: package com.herp.pattern.strategy;22:
33: import java.io.*;
44:
55: public class BasicFileOutput {
66: static String file = "BasicFileOutput.out";
77:
88: public static void main(String[] args) throws IOException {
99: BufferedReader in = new BufferedReader(new StringReader(BufferedInutFile.readFile("f:/BasicFileOutput")));
1010: PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
1111:
1212: int lineCount = 1;
1313: String s;
1414: while ((s = in.readLine()) != null){
1515: out.println(lineCount ++ + ": " + s);
1616: }
1717: out.close();
1818: in.close();
1919: }
2020: }
数据的存储和恢复