-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInputStreamReaderTest.java
More file actions
107 lines (95 loc) · 2.93 KB
/
Copy pathInputStreamReaderTest.java
File metadata and controls
107 lines (95 loc) · 2.93 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package tutorial.java;
import org.junit.Test;
import java.io.*;
public class InputStreamReaderTest {
@Test
public void test(){
FileInputStream fis = null;
InputStreamReader isr = null;
try {
fis = new FileInputStream("test.txt");
/* charset
* what type of charset need to use, depends on in what way the srcFile saved.
* if it's saved using UTF-8, then we need to use that as the charset
*
* UTF-8 is set by default though
* */
// default
isr = new InputStreamReader(fis);
// isr = new InputStreamReader(fis, "UTF-8");
// isr = new InputStreamReader(fis, "gbk"); // garbled
int len;
char[] cbuf = new char[10];
while((len = isr.read(cbuf)) != -1){
String data = new String(cbuf, 0, len);
System.out.println(data);
}
}catch (IOException e){
e.printStackTrace();
}finally {
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isr != null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/* using InputStreamReader (utf8) && OutputStreamWriter (gbk) */
@Test
public void test2(){
FileOutputStream fos = null;
FileInputStream fis = null;
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
fis = new FileInputStream("test.txt");
fos = new FileOutputStream("test_gbk.txt");
isr = new InputStreamReader(fis);
osw = new OutputStreamWriter(fos, "gbk");
int len;
char[] cbuf = new char[10];
while( (len= isr.read(cbuf))!= -1){
osw.write(cbuf, 0, len);
}
}catch (IOException e){
e.printStackTrace();
}finally {
if( osw!= null){
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}if(isr != null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}