【问题标题】:How to print arrayList to text file?如何将arrayList打印到文本文件?
【发布时间】:2018-08-13 03:54:21
【问题描述】:

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

当我使用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");
    }
}

【问题讨论】:

  • 这个构造函数没必要用,有new PrintWriter("project.txt")这样更简单的构造函数。还有现在应该使用的try-with-resourcesNIO

标签: java io text-files


【解决方案1】:

我确定文件在某处,您的代码没有错误。至少,我没有看到。也许您需要调用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);

就是这样,很简单。

【讨论】:

    猜你喜欢
    • 2015-05-05
    • 1970-01-01
    • 2017-08-07
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 2012-08-25
    相关资源
    最近更新 更多