2015-02-22 16:16

[Java] 檔案讀寫

FileReader & FileWriter
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

public class FileReadWrite1 {

    public static void main(String[] args) throws Exception {

        FileReader fReader = new FileReader("input.txt");
        FileWriter fWriter = new FileWriter("output.txt");

        /* Buffered 提供單行讀取的功能 */
        BufferedReader bReader = new BufferedReader(fReader);
        BufferedWriter bWriter = new BufferedWriter(fWriter);

        String line;
        while ((line = bReader.readLine()) != null) {
            System.out.println(line);
            bWriter.write(line);
            bWriter.newLine();
        }

        bReader.close();
        bWriter.close();
    }
}


InputStreamReader & OutputStreamWriter
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileReadWrite2 {

    public static void main(String[] args) throws Exception {

        InputStreamReader fReader = new InputStreamReader(
            new FileInputStream("input.txt"), "UTF8"
        );
        OutputStreamWriter fWriter = new OutputStreamWriter(
            new FileOutputStream("output.txt"), "UTF8"
        );

        /* Buffered 提供單行讀取的功能 */
        BufferedReader bReader = new BufferedReader(fReader);
        BufferedWriter bWriter = new BufferedWriter(fWriter);

        String line;
        while ((line = bReader.readLine()) != null) {
            System.out.println(line);
            bWriter.write(line);
            bWriter.newLine();
        }

        bReader.close();
        bWriter.close();
    }
}

0 回應: