javafilejava-11filewriterexport-csv

File createNewFile() Fails If-Statement When File length() Does Not


What are the details of your problem?

Why does the If-Statement of file.createNewFile() not seem to trigger?

The file does create and does do fileWriter.append() after this if-statement.
If I create a if (!file.createNewFile()) this triggers every time after.
The file does append on the file.length()==0.

Why does the file create and append fine but the if block doesn't work?

What did you try and what were you expecting?

I've tried to whittle down my problem to the smallest snippet for illustration.
If instead I should be making the smallest readily run program, let me know and I will update this.

            String exportFilePath = "some/where/to/export/file.csv";
            FileWriter fileWriter = new FileWriter(exportFilePath, true);
            File file = new File(exportFilePath);
            if (file.createNewFile()) {
                System.out.println("Created File:\t" + file);

                // This Does Not Work 
                fileWriter.append(String.join(",", headers))
                        .append("\n")
                        .close();
            }
            if (file.length()==0)

                // This Does Work 
                fileWriter.append(String.join(",", headers))
                        .append("\n")
                        .close();

Solution

  • Issue was with me not understanding that File file = new File(exportFilePath); creates the file on at least the latest Java 11.0.16+11.

    I was able to remove all of that and now the code works as this:

            File file = new File(exportFilePath);
            if (file.length() == 0) fileWriter.append(String.join(",", headers)).append("\n");
            fileWriter.append(String.join(",", currentLine)).append("\n").close();