如何将arrayList打印到文本文件?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将arrayList打印到文本文件?相关的知识,希望对你有一定的参考价值。

我想将ArrayListprojects)中的对象作为字符串打印到文件中。它们当前存储为“项目”,在不同的类中定义。

当我使用System.out.print而不是outputStream.print时,它工作正常,信息按预期显示。只要我想在文件中,该文件就不会出现。

import java.io.PrintWriter;
import java.util.ArrayList;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;

public class FileController
{
    public static void finish(ArrayList<Project> projects) 
    {
        PrintWriter outputStream = null;            
        try 
        {
            outputStream = new PrintWriter(new FileOutputStream("project.txt"));
        }
        catch (FileNotFoundException e)
        {
            System.out.println("Error opening the file stuff.txt.");
            System.exit(0);
        }
        System.out.println("Writing to file");

        for(int i = 0; i < projects.size(); i++)
        {
            //System.out.print(projects.get(i) + "," + projects.get(i).teamVotes);
            outputStream.println(projects.get(i) + "," + projects.get(i).teamVotes);

        }

        outputStream.close();

        System.out.println("End of Program");
    }
}
答案

我确定文件在某个地方,你的代码没有错误。至少,我没有看到任何。也许你需要调用outputStream.flush(),因为你使用的构造函数使用来自给定OutputStream的自动行刷新,请参阅documentation。但afaik关闭流将自动刷新。

您的路径"project.txt"是相对的,因此该文件将放置在您的代码执行的位置。通常,这是在.class文件附近,检查项目中的所有文件夹。

你也可以试试像这样的绝对路径

System.getProperty("user.home") + "/Desktop/projects.txt"

然后你会很容易找到该文件。


无论如何,您现在应该使用Javas NIO来编写和读取文件。它围绕着类FilesPathsPath。然后代码可能看起来像

// Prepare the lines to write
List<String> lines = projects.stream()
    .map(p -> p + "," + p.teamVotes)
    .collect(Collectors.toList());

// Write it to file
Path path = Paths.get("project.txt");
Files.write(path, lines);

就是这样,很容易。

以上是关于如何将arrayList打印到文本文件?的主要内容,如果未能解决你的问题,请参考以下文章

打印到文本文件[重复]

将视图和片段保存在文件中

如何更新 Tablayout 中的片段? (Viewpager2, FragmentStateAdapter)

如何拆分包含 String 和 Int 的文本并存储到 ArrayList 中?

如何使用python3将输入数据存储到文本文件中并打印数据输出?

把ArrayList集合的字符串存储到文本文件/把文本文件的数据存储到ArrayList集合中