forked from JustinSDK/JavaSE6Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamWriterDemo.java
More file actions
60 lines (51 loc) · 1.99 KB
/
StreamWriterDemo.java
File metadata and controls
60 lines (51 loc) · 1.99 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
package onlyfun.caterpillar;
import java.io.*;
public class StreamWriterDemo {
public static void main(String[] args) {
try {
// 「簡體中文」四個字的 GB2312 編碼
byte[] sim = {(byte)0xbc, (byte)0xf2,
(byte)0xcc, (byte)0xe5,
(byte)0xd6, (byte)0xd0,
(byte)0xce, (byte)0xc4};
// 陣列作為串流來源
ByteArrayInputStream byteArrayInputStream =
new ByteArrayInputStream(sim);
InputStreamReader inputStreamReader =
new InputStreamReader(
byteArrayInputStream, "GB2312");
// PrintWriter還接受Writer實例作為引數
PrintWriter printWriter =
new PrintWriter(
new OutputStreamWriter(
new FileOutputStream(args[0]), "GB2312"));
int in = 0;
printWriter.print("PrintWriter: ");
// 寫入陣列內容
while((in = inputStreamReader.read()) != -1) {
printWriter.print((char)in);
}
printWriter.println();
printWriter.close();
byteArrayInputStream.reset();
// PrintStream 接受OutputStream實例作為引數
PrintStream printStream =
new PrintStream(new FileOutputStream(args[0], true),
true, "GB2312");
printStream.print("PrintStream: ");
// 寫入陣列內容
while((in = inputStreamReader.read()) != -1) {
printStream.print((char)in);
}
printStream.println();
inputStreamReader.close();
printStream.close();
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("沒有指定檔案");
}
catch(IOException e) {
e.printStackTrace();
}
}
}