java IO 读文件 写文件

版权声明:此博客内容均是本人精心整理文档,方便大家学习交流,如有不妥之处,请联系我删除 https://blog.csdn.net/u012489091/article/details/82529297

今天,线上出了一点问题,需要通过查看日志才能解决。最终,也的确是通过查看日志解决了问题。接着就需要对日志文件进行过滤,查询日志文件中我们想要的数据,然后存入库中。
于是写了一个简单的读写文件操作。日后再使用的时候,我就不再去写了,直接copy就好了。方便的记录一下:

    /**
     * 提供路径,以行为单位读取数据
     * 以行为单位读取文件,常用于读面向行的格式化文件
     */
    public static List<JSONObject> readFileByLines(String fileName) {
        List<JSONObject> listRes = new ArrayList<>();

        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            JSONObject jsonObject = null;
            String tempString = null;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // TODO tempString 就是我们读取到的那一行的内容,我们也可以进行我们自己的相应的业务的处理
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return listRes;
    }
    /**
     * 将 内容 输入到 文本中
     * @param filePath 文件路径
     * @param content 输出内容
     */
    private static void contentToFile(String filePath, String content) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.out.println(e.getMessage() + "文件创建失败,路径是:" + filePath);
            }
        }

        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e1) {
                }
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/u012489091/article/details/82529297