0

I'm writing this class that has a method to create a csv file and to write in to it. The problem is that it throws IOException error before the file is even created.

This is a class on its own, and the method is being called from another class.

The code looks like this:

public class WriteCSV {

    public WriteCSV () {

    }
    public void writeToFile(Movie movie) {

        try {
            BufferedWriter out = new BufferedWriter(new FileWriter("ratings.csv"));
            out.write(movie.getId() +";" + movie.getTitle() + ";" + movie.getDuration() +";" + movie.getImg() + ";" + movie.getStars());
            out.close();
        }
        catch (IOException ex) {
            System.out.println("Error");
        }
    }
}
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
OttoIEM
  • 21
  • 4
  • Add `ex.printStackTrace();` to your `catch` block and add the output to your question. See https://stackoverflow.com/questions/2560368/what-is-the-use-of-printstacktrace-method-in-java for some info – PM 77-1 Jul 29 '22 at 18:03
  • `ratings.csv` is not a valid filesystem path. You need to use a complete path. The simplest solution overall is to get one using root directories provided by a `Context`, such as `getFilesDir()`. So, `new FileWriter("ratings.csv")` would become `new FileWriter(new File(ctx.getFilesDir(), "ratings.csv"))`, where `ctx` is a suitable `Context`. – CommonsWare Jul 29 '22 at 18:15
  • I added the ctx.getFilesDir(), now there is an error: "Cannot resolve constructor 'FileWriter(java.io.File, java.lang.String)'". I added the code just like you showed. I am not too familiar with context, should I somehow specify it? – OttoIEM Jul 30 '22 at 06:14

0 Answers0