FileReader實現讀取文件內容並輸出到屏幕上

FileReader與FileInputStream都是從文件讀數據,而前者一次讀一個字符,後者一次讀一個字節(在Unicode編碼環境下1個字符=2個字節)java

package com.janson.day20180827;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestFileReader {
    public static void main(String[] args) {
        FileReader reader = null;
        int f = 0;
        try {
            reader = new FileReader(System.getProperty("user.dir") + "\\src\\com\\janson\\day20180827\\TestFileReader.java");
        }catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("找不到相應文件");
        }

        try {
            while ((f=reader.read())!=-1) {
                System.out.print((char)f);
            }
        }catch (IOException e) {
            e.printStackTrace();
            System.out.println("讀取文件出錯");
        }
    }
}
相關文章
相關標籤/搜索