【Java】将List写入文件以及将文件读为List

 将List写入文件:

public void writeList2File(List<Long> lines, String filePath) {
        File file = new File(filePath);
        // 判断文件是否存在
        if (!file.exists()) {
            file.createNewFile();
        }
        // 遍历写入
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        for (long lineL : lines) {
            bw.write(long2DateString(lineL) + "\r\n");
        }
        bw.flush();
        bw.close();
}

  将文件读为List:

public ArrayList<String> readFile2List() {
        // 获取到文件流
        File inputFile = new File("D:\\dir\\file.txt");
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(inputFile));
        BufferedReader br = new BufferedReader(inputStreamReader);

        // 将文件读到 List中
        String line = null;
        ArrayList<String> lines = Lists.newArrayList();
        while ((line = br.readLine()) != null) {
            lines.add(line);
        }
        return lines;
    }

 

posted @ 2021-10-31 17:40  vickylinj  阅读(3037)  评论(0编辑  收藏  举报