0

I want to print the objects within an ArrayList (projects) to a file as a string. They are currently stored as 'Projects' which is defined in a different class.

When I use System.out.print rather than outputStream.print, it works fine, and the information appears as expected. As soon as I want it in a file, the file doesn't appear.

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");
    }
}
Jacob
  • 72,750
  • 22
  • 137
  • 214
Steadw
  • 1
  • 1
  • There's no need to use this constructor, there are easier ones like `new PrintWriter("project.txt")`. There is also **try-with-resources** and **NIO** that should be used nowadays. – Zabuzard Mar 05 '18 at 23:42

1 Answers1

0

I'm sure the file is somewhere, your code has no errors. At least, I don't see any. Maybe you need to call outputStream.flush() since the constructor you are using uses automatic line flushing from the given OutputStream, see the documentation. But afaik closing the stream will flush automatically.

Your path "project.txt" is relative, so the file will be placed where your code is being executed. Usually, that is near the .class files, check all folders around there in your project.

You can also try an absolute path like

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

then you will easily find the file.


Anyways, you should use Javas NIO for writing and reading files now. It revolves around the classes Files, Paths and Path. The code may then look like

// 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);

and that's it, easy.

Zabuzard
  • 20,717
  • 7
  • 45
  • 67