-
Notifications
You must be signed in to change notification settings - Fork 1
/
test-merge.txt
92 lines (84 loc) · 3.37 KB
/
test-merge.txt
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
sunzjlhufy
hahapackage com.momolela.io;
import java.io.*;
public class IO06FileCopyByBuf {
public static void main(String[] args) throws Exception {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("test.txt"));
bw = new BufferedWriter(new FileWriter("test-copy.txt"));
String line = null;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
} catch (IOException e) {
throw new Exception("文件复制失败");
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException e) {
throw new Exception("关闭写入流缓冲区失败");
}
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
throw new Exception("关闭读出流缓冲区失败");
}
}
}
}
package com.momolela.io;
import java.io.*;
public class IO13TransformStream {
public static void main(String[] args) {
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
// System.setIn(new FileInputStream("test.txt")); // 可以通过 System.setIn 改变 System.in 的标准输入对象
// System.in 的类型是 InputStream ,是一个字节流,通过 InputStreamReader 变成了一个字符流,然后再通过 BufferedReader 的包装,可以使用 readLine() 和 newLine() 的功能
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
// 将输出从控制台改为文件
System.setOut(new PrintStream("test-system-out.txt"));
// System.out 的类型是 PrintStream 最终继承自 OutputStream ,是一个字节流,通过 OutputStreamWriter 变成了一个字符流,然后再通过 BufferedWriter 的包装
bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out, "utf-8")); // 在使用转换流的时候,可以指定编码
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if ("over".equals(line)) {
break;
}
bufferedWriter.write(line);
bufferedWriter.newLine();
bufferedWriter.flush(); // 字符流需要 flush 刷入
}
} catch (IOException e) {
try {
// 日志异常系统,就可以用这样的方式进行输出
e.printStackTrace(new PrintStream("test-exception.log"));
} catch (FileNotFoundException fileNotFoundException) {
throw new RuntimeException("异常日志文件写出失败");
}
} finally {
try {
if (bufferedWriter != null) {
bufferedWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}