Java IO把一個文件中的內容以字符串的形式讀出來

代碼記錄(備查):java

/**
 * 把一個文件中的內容以字符串的形式讀出來
 * 
 * @author zhipengs
 * 
 */
public class FileToString {
    public static void main(String[] args) {
        System.out.println(readFileToString());
    }

    private static String readFileToString() {
        // new 一個空文件,用於獲取路徑
        File dirs = new File(".");
        BufferedReader reader = null;
        StringBuilder fileData = null;
        try {
            String filePath = dirs.getCanonicalPath() + File.separator + "src"
                    + File.separator + "TestRead.java";

            fileData = new StringBuilder(1000);
            reader = new BufferedReader(new FileReader(filePath));

            char[] buf = new char[1024];
            int numRead = 0;
            while ((numRead = reader.read(buf)) != -1) {
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
                buf = new char[1024];
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != reader)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileData.toString();
    }
}
相關文章
相關標籤/搜索