forked from JustinSDK/JavaSE6Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathByteArrayStreamDemo.java
More file actions
62 lines (53 loc) · 2.15 KB
/
ByteArrayStreamDemo.java
File metadata and controls
62 lines (53 loc) · 2.15 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
package onlyfun.caterpillar;
import java.io.*;
import java.util.*;
public class ByteArrayStreamDemo {
public static void main(String[] args) {
try {
File file = new File(args[0]);
BufferedInputStream bufferedInputStream =
new BufferedInputStream(
new FileInputStream(file));
ByteArrayOutputStream arrayOutputStream =
new ByteArrayOutputStream();
byte[] bytes = new byte[1];
// 將檔案內容寫入位元陣列串流
while(bufferedInputStream.read(bytes) != -1) {
arrayOutputStream.write(bytes);
}
arrayOutputStream.close();
bufferedInputStream.close();
// 以字元方式顯示位元陣列內容
bytes = arrayOutputStream.toByteArray();
for(int i = 0; i < bytes.length; i++) {
System.out.print((char) bytes[i]);
}
System.out.println();
// 讓使用者輸入位置與字元修改位元陣列內容
Scanner scanner = new Scanner(System.in);
System.out.print("輸入修改位置:");
int pos = scanner.nextInt();
System.out.print("輸入修改字元:");
// 修改陣列中對應的字元
bytes[pos-1] = (byte) scanner.next().charAt(0);
// 將位元陣列內容存回檔案
ByteArrayInputStream byteArrayInputStream =
new ByteArrayInputStream(bytes);
BufferedOutputStream bufOutputStream =
new BufferedOutputStream(
new FileOutputStream(file));
byte[] tmp = new byte[1];
while(byteArrayInputStream.read(tmp) != -1)
bufOutputStream.write(tmp);
byteArrayInputStream.close();
bufOutputStream.flush();
bufOutputStream.close();
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("請指定檔案名稱");
}
catch(IOException e) {
e.printStackTrace();
}
}
}