Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java I/O 九個課堂範例:位元組流、字元流與檔案操作全解析

Java 的輸入輸出是初學者最容易混淆的一塊:位元組流與字元流有什麼差別?DataOutputStream 寫入 double,讀回來要用哪個方法?BufferedReader 為什麼要包一層?下面用九個由淺入深的小範例把這些觀念串起來,每個範例都是把註解打開就能直接執行的形式。

範例一:逐行搬移檔案內容

以字元流讀入 in.txt,為每一行加上行號後寫到 out.txt。這裡示範了「串接流」的經典組合:FileReader 負責 bytes→chars 的解碼,BufferedReader 提供 readLine 的方便,PrintWriter 則負責格式化輸出。

package com.lecheng;

import java.io.*;

public class MainTest {
    public static void main(String[] args) {
        // 範例 1:從一個檔案讀資料,處理後存入另一個檔案
        try {
            BufferedReader in = new BufferedReader(new FileReader("in.txt"));
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new FileWriter("out.txt")));
            String s;
            int i = 1;
            while ((s = in.readLine()) != null) {
                out.println("line " + i + "=" + s);
                i++;
            }
            in.close();
            out.close();
            System.out.println("完成!");
        } catch (FileNotFoundException e) {
            System.err.println("無法打開 in.txt");
        } catch (IOException e) {
            System.err.println("I/O exception");
        }
    }
}

範例二:從鍵盤讀字元流

try {
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader is = new BufferedReader(isr);
    String inputLine;
    while ((inputLine = is.readLine()) != null) {
        System.out.println(inputLine);
    }
    is.close();
} catch (IOException e) {
    System.out.println("IOException: " + e);
}

System.in 本質上是一個位元組串流,InputStreamReader 是位元組轉字元的橋樑,這也是所有「讀鍵盤」寫法的起點。

範例三與四:用 DataOutputStream 混合寫入多種型別

DataOutputStream 的好處是可以直接把 int、double、boolean 等基本型別寫進檔案,不必自己轉字串。範例中把一個 StudentPojo 的 five 個欄位依序寫入,並用 writeChar('\n') 當作分隔符號。

try {
    StudentPojo stu = new StudentPojo(1, "張三", "石家莊", 56.8, false);
    FileOutputStream fout = new FileOutputStream("text.txt");
    DataOutputStream out = new DataOutputStream(fout);
    out.writeInt(stu.getId());        out.writeChar('\n');
    out.writeChars(stu.getName());    out.writeChar('\n');
    out.writeChars(stu.getAddress()); out.writeChar('\n');
    out.writeDouble(stu.getWeight()); out.writeChar('\n');
    out.writeBoolean(stu.isSex());
    out.close();
} catch (IOException e) { }

讀取時必須以完全相同的型別與順序還原,這也是二進位格式的特性——格式一錯,資料就全亂:

DataInputStream in = null;
try {
    in = new DataInputStream(new FileInputStream("text.txt"));
    int id;
    StringBuffer name, address;
    double weight;
    boolean sex;
    char ch;
    while (true) {
        id = in.readInt();
        in.readChar();
        name = new StringBuffer(20);
        while ((ch = in.readChar()) != '\n') name.append(ch);
        address = new StringBuffer(20);
        while ((ch = in.readChar()) != '\n') address.append(ch);
        weight = in.readDouble();
        in.readChar();
        sex = in.readBoolean();
        System.out.println("ID:" + id);
        System.out.println("姓名:" + name);
        System.out.println("住址:" + address);
        System.out.println("體重:" + weight);
        System.out.println("性別:" + sex);
    }
} catch (IOException e) { }

範例五:以 FileInputStream / FileOutputStream 複製檔案

try {
    File inFile = new File("in.txt");
    File outFile = new File("out.txt");
    FileInputStream fis = new FileInputStream(inFile);
    FileOutputStream fos = new FileOutputStream(outFile);
    int c;
    while ((c = fis.read()) != -1) {
        fos.write(c);
    }
    fis.close();
    fos.close();
} catch (FileNotFoundException e) {
    System.err.println("FileStreamsTest: " + e);
} catch (IOException e) {
    System.err.println("FileStreamsTest: " + e);
}

一次讀一個位元組雖然直觀,效率卻不理想;實務上會包上 BufferedInputStream 或改用 byte[] 緩衝區一次搬 4KB,差距可達數十倍。

範例六:走訪目錄並取得檔案資訊

File files = new File("c:\\");
String fileList[] = files.list();
for (int i = 0; i < fileList.length; i++) {
    File currfiles = new File("c:\\" + fileList[i]);
    System.out.print("文件名:" + fileList[i] + "\t");
    System.out.println("文件大小:" + currfiles.length());
}

File 類別不只代表檔案,也代表目錄。list() 回傳子項名稱陣列,length() 取得位元組大小,若要一併取得修改時間與是否為目錄,可再用 lastModified() 與 isDirectory()。

範例七:鍵盤輸入寫入檔案

try {
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    FileWriter fw = new FileWriter("char.txt");
    BufferedWriter bw = new BufferedWriter(fw);
    String str;
    while (true) {
        System.out.print("請輸入一個字符串:");
        System.out.flush();
        str = br.readLine();
        if (str.length() == 0) break;   // 空白行結束輸入
        bw.write(str);
        bw.newLine();
    }
    bw.close();
} catch (IOException e) {
    System.out.println("IOException: " + e);
}

範例八與九:從檔案讀出並顯示

第八個範例用 System.out.println 直接印到螢幕:

try {
    FileReader fr = new FileReader("char.txt");
    BufferedReader br = new BufferedReader(fr);
    int lineNum = 0;
    String str = br.readLine();
    while (str != null) {
        lineNum++;
        System.out.println("第" + lineNum + "行:" + str);
        str = br.readLine();
    }
} catch (IOException e) {
    System.out.println("IOException: " + e);
}

第九個範例則改用串流方式輸出,把 System.out 包成 OutputStreamWriter 再包成 BufferedWriter,示範「輸出一側也能串接」:

try {
    FileReader fr = new FileReader("char.txt");
    BufferedReader br = new BufferedReader(fr);
    OutputStreamWriter osw = new OutputStreamWriter(System.out);
    BufferedWriter bw = new BufferedWriter(osw);
    int lineNum = 0;
    String str = br.readLine();
    while (str != null) {
        lineNum++;
        bw.write(String.valueOf(lineNum));
        bw.write(" ");
        bw.write(str);
        bw.newLine();
        str = br.readLine();
    }
    bw.close();
} catch (IOException e) {
    System.out.println("IOException: " + e);
}

附:範例使用的 POJO

package com.lecheng;

public class StudentPojo {
    private int id;
    private String name;
    private String address;
    private double weight;
    private boolean sex;

    public StudentPojo(int id, String name, String address, double weight, boolean sex) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.weight = weight;
        this.sex = sex;
    }

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getAddress() { return address; }
    public void setAddress(String address) { this.address = address; }

    public double getWeight() { return weight; }
    public void setWeight(double weight) { this.weight = weight; }

    public boolean isSex() { return sex; }
    public void setSex(boolean sex) { this.sex = sex; }
}

把九個範例攤開來看,Java I/O 的脈絡其實很清楚:最底層是四個基本類別(FileInputStream/FileOutputStream 位元組、FileReader/FileWriter 字元),外面再依需求套上緩衝、格式化或型別處理的裝飾器。理解「每一層各自負責什麼」,比死記組合寫法有用得多。另外別忘了養成關流或用 try-with-resources 的習慣,才能避免檔案描述符洩漏。

Copyright © Linux教程網 All Rights Reserved