【发布时间】: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-resources和NIO。
标签: java io text-files