Java之美[从菜鸟到高手演变]之Java中的IO (四)

2014-11-24 11:03:47 · 作者: · 浏览: 2
("data.d")); // testing is OK!
90.
91. /* write() test */
92. write("out.d", "helloworld\negg"); // testing is OK!
93.
94. /* constractor test */
95. TextFile tf = new TextFile("data.d"); // testing is OK!
96.
97. }
98.
99.}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;

/**
* 一个非常实用的文件操作类 . 2012-12-19
*
* @author Bruce Eckel , edited by erqing
*
*/
public class TextFile extends ArrayList {

private static final long serialVersionUID = -1942855619975438512L;

// Read a file as a String
public static String read(String filename) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader(new File(
filename).getAbsoluteFile()));
String s;
try {
while ((s = in.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} finally {
in.close();
}

} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}

// Write a single file in one method call
public static void write(String fileName, String text) {
try {
PrintWriter out = new PrintWriter(
new File(fileName).getAbsoluteFile());
try {
out.print(text);
} finally {
out.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

// Read a file,spilt by any regular expression
public TextFile(String fileName, String splitter) {
super(Arrays.asList(read(fileName).split(splitter)));
if (get(0).equals(""))
remove(0);
}

// Normally read by lines
public TextFile(String fileName) {
this(fileName, "\n");
}

public void write(String fileName) {
try {
PrintWriter out = new PrintWriter(
new File(fileName).getAbsoluteFile());
try {
for (String item : this)
out.println(item);
} finally {
out.close();
}

} catch (IOException e) {
throw new RuntimeException(e);
}

}

// test,I have generated a file named data.d at the root
public static void main(String[] args) {

/* read() test */
System.out.println(read("data.d")); // testing is OK!

/* write() test */
write("out.d", "helloworld\negg"); // testing is OK!

/* constractor test */
TextFile tf = new TextFile("data.d"); // testing is OK!

}

}2、读取二进制文件。

[java]
01.import java.io.BufferedInputStream;
02.import java.io.File;
03.import java.io.FileInputStream;
04.import java.io.IOException;
05.
06./**
07. * to read the binary file
08. *
09. * @author erqing
10. *
11. */
12.public class BinaryFile {
13.
14. /* the parametre is a file */
15. public static byte[] read(File file) throws IOException {
16. BufferedInputStream bf = new BufferedInputStream(new FileInputStream(
17. file));
18. try {
19. byte[] data = new byte[bf.available()];
20. bf.read(data);
21. return data;
22. } finally {
23. bf.close();
24. }
25. }
26.
27. /* the param is the path of a file */
28. public static byte[] read(String file) throws IOException {
29. return read(new File(file).getAbsoluteFile());
30. }
31.}