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

2014-11-24 11:03:47 · 作者: · 浏览: 3
.err都是直接的PriintStream对象,可直接使用。我们也可以使用java.util包下的Scanner类来代替上述程序:

[java]
01.public class StandardIO {
02.
03. public static void main(String[] args) throws IOException {
04. Scanner in = new Scanner(System.in);
05. String s;
06. while((s = in.next()) != null && s.length() != 0){
07. System.out.println(s);
08. }
09. }
10.}
public class StandardIO {

public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
String s;
while((s = in.next()) != null && s.length() != 0){
System.out.println(s);
}
}
}九、性能分析及总结

1、一个文件读写工具类。

[java]
01.import java.io.BufferedReader;
02.import java.io.File;
03.import java.io.FileReader;
04.import java.io.IOException;
05.import java.io.PrintWriter;
06.import java.util.ArrayList;
07.import java.util.Arrays;
08.
09./**
10. * 一个非常实用的文件操作类 . 2012-12-19
11. *
12. * @author Bruce Eckel , edited by erqing
13. *
14. */
15.public class TextFile extends ArrayList {
16.
17. private static final long serialVersionUID = -1942855619975438512L;
18.
19. // Read a file as a String
20. public static String read(String filename) {
21. StringBuilder sb = new StringBuilder();
22. try {
23. BufferedReader in = new BufferedReader(new FileReader(new File(
24. filename).getAbsoluteFile()));
25. String s;
26. try {
27. while ((s = in.readLine()) != null) {
28. sb.append(s);
29. sb.append("\n");
30. }
31. } finally {
32. in.close();
33. }
34.
35. } catch (IOException e) {
36. throw new RuntimeException(e);
37. }
38. return sb.toString();
39. }
40.
41. // Write a single file in one method call
42. public static void write(String fileName, String text) {
43. try {
44. PrintWriter out = new PrintWriter(
45. new File(fileName).getAbsoluteFile());
46. try {
47. out.print(text);
48. } finally {
49. out.close();
50. }
51. } catch (IOException e) {
52. throw new RuntimeException(e);
53. }
54. }
55.
56. // Read a file,spilt by any regular expression
57. public TextFile(String fileName, String splitter) {
58. super(Arrays.asList(read(fileName).split(splitter)));
59. if (get(0).equals(""))
60. remove(0);
61. }
62.
63. // Normally read by lines
64. public TextFile(String fileName) {
65. this(fileName, "\n");
66. }
67.
68. public void write(String fileName) {
69. try {
70. PrintWriter out = new PrintWriter(
71. new File(fileName).getAbsoluteFile());
72. try {
73. for (String item : this)
74. out.println(item);
75. } finally {
76. out.close();
77. }
78.
79. } catch (IOException e) {
80. throw new RuntimeException(e);
81. }
82.
83. }
84.
85. // test,I have generated a file named data.d at the root
86. public static void main(String[] args) {
87.
88. /* read() test */
89. System.out.println(read