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();
    }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区