Java 基於字元的IO Char Based IO

weixin_34236869發表於2016-12-14

FileReader & FileWriter

讀寫格式:按字元讀寫,每次讀寫一個字元,或者讀寫一個字元陣列。

public static void main(String[] args) throws Exception {
    FileReader fread = new FileReader("a.txt");
    FileWriter fwriter = new FileWriter("b.txt");

    int c;
    while ((c = fread.read()) != -1) {
        System.out.print((char) c);

        fwriter.write(c);
    }

    fwriter.flush();
}

使用緩衝流 BufferedReader & BufferedWriter

讀寫格式:按字元讀寫,每次讀寫一個字元,或者讀寫一個字元陣列,或者讀寫一個字串 String。

public static void main(String[] args) throws Exception {
    BufferedReader breader = new BufferedReader(new FileReader("a.txt"));
    BufferedWriter bwriter = new BufferedWriter(new FileWriter("b.txt"));

    String s;
    while ((s = breader.readLine()) != null) {
        System.out.print(s);

        bwriter.write(s);
    }

    bwriter.flush();
}

PrintWriter

public static void main(String[] args) throws Exception {
    PrintWriter pw = new PrintWriter(System.out);

    pw.println("Hello World");

    pw.flush();
}

相關文章