Java IO 的類別多到讓人卻步,但位元組流其實只有幾種固定組合。以下用四個可執行的範例,把最常見的讀寫模式跑一遍。
public static void main(String[] args) throws Exception {
File f = new File("d:\\demo.txt");
// 寫入
FileOutputStream output = new FileOutputStream(f);
String s = "I Am Learning Java , 我在學習Java";
byte[] b = s.getBytes();
// output.write(b); 也可以一次寫入整個陣列
for (int i = 0; i < b.length; i++) {
output.write(b[i]);
}
output.flush();
output.close();
// 讀取
FileInputStream input = new FileInputStream(f);
byte[] in = new byte[(int) f.length()];
for (int i = 0; i < in.length; i++) {
in[i] = (byte) input.read();
}
System.out.print(new String(in));
input.close();
}
關鍵觀念:write 可以接受 byte 陣列或單一 byte;read 單次只取一個位元組,讀到底會回傳 -1。
public static void main(String[] args) throws Exception {
File f = new File("d:\\demo.txt");
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(f));
String s = "I Am Learning Java , 我在學習Java";
output.write(s.getBytes()); // 預設 512 位元組緩衝,期滿才實際落盤
output.flush();
output.close();
BufferedInputStream input = new BufferedInputStream(new FileInputStream(f));
byte[] in = new byte[(int) f.length()];
for (int i = 0; i < in.length; i++) {
in[i] = (byte) input.read();
}
System.out.println(new String(in));
input.close();
}
裝飾器模式的典型應用:把緩衝流套在節點流外面,讀寫次數相同但實際的系統呼叫大幅減少。記得 flush,否則緩衝區中的資料可能不會寫入檔案。
這一組的好處是不必自己處理「字串多長、整數佔幾個 byte」的問題,寫入時是什麼型別,讀出來就是什麼型別。
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return this.name; }
public int getAge() { return this.age; }
}
public static void main(String[] args) {
Person[] p1 = { new Person("Ryan", 20), new Person("Tom", 30), new Person("Jerry", 15) };
File f = new File("d:\\demo\\demo.txt");
try {
DataOutputStream output = new DataOutputStream(new FileOutputStream(f));
for (int i = 0; i < p1.length; i++) {
output.writeUTF(p1[i].getName()); // 以 UTF 編碼寫入姓名
output.writeInt(p1[i].getAge()); // 以 int 寫入年齡
}
output.flush();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
Person[] p2 = new Person[p1.length];
try {
DataInputStream input = new DataInputStream(new FileInputStream(f));
for (int i = 0; i < p1.length; i++) {
String name = input.readUTF();
int age = input.readInt();
p2[i] = new Person(name, age);
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < p2.length; i++) {
System.out.println("姓名:" + p2[i].getName() + " ;年齡:" + p2[i].getAge());
}
}
注意:讀取順序必須與寫入順序完全一致,否則型別錯位會直接拋出 IOException。
public static void main(String[] args) {
File f = new File("d:\\demo.txt");
String studentName = "TOM";
int age = 20;
double totalScore = 600.0f;
PrintStream ps = null;
try {
ps = new PrintStream(new FileOutputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ps.printf("姓名:%s , 年齡:%d , 總分:%3.1f", studentName, age, totalScore);
}
純位元組搬運用 File 流;量大就用 Buffered 包一層;需要存基本型別用 Data 流;要格式化輸出用 PrintStream。不論哪一種,flush 與 close 都不能省——close 通常會隱含 flush,但養成習慣能避開大量「檔案內容不完整」的靈異事件。