Java IO把一个文件中的内容以字符串的形式读出来

代码记录(备查):

/**
 * 把一个文件中的内容以字符串的形式读出来
 * 
 * @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();
    }
}

 

posted @ 2014-05-25 17:04  知了小巷  阅读(1570)  评论(0编辑  收藏  举报