java读写file

 private static String encoding = "utf-8";

    public static void readTxt(String filePath) throws IOException {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file), encoding);
            BufferedReader bfr = new BufferedReader(read);
            String lineTxt = null;
            while ((lineTxt = bfr.readLine()) != null) {
                System.out.println(lineTxt);
            }
            read.close();
            bfr.close();
        }
    }

    public static String readFile(String path) throws IOException {
        FileReader fileReader = new FileReader(path);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String lineTxt = null;
        StringBuffer sb = new StringBuffer();
        while ((lineTxt = bufferedReader.readLine()) != null) {
            sb.append(lineTxt);
        }
        bufferedReader.close();
        fileReader.close();

        return sb.toString();
    }

    public static void writeTxt(String path, String data) throws IOException {
        FileWriter fileWriter = new FileWriter(path);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(data);
        bufferedWriter.close();
        fileWriter.close();
    }

  

posted @ 2016-04-26 21:48  Ryan.Miao  阅读(284)  评论(0编辑  收藏  举报