The system cannot find the path specified with FileWriter
Asked Answered
L

3

9

I have this code:

private static void saveMetricsToCSV(String fileName, double[] metrics) {
        try {
            FileWriter fWriter = new FileWriter(
                    System.getProperty("user.dir") + "\\output\\" +
                    fileTimestamp + "_" + fileDBSize + "-" + fileName + ".csv"
            );

            BufferedWriter csvFile = new BufferedWriter(fWriter);

            for(int i = 0; i < 4; i++) {
                for(int j = 0; j < 5; j++) {
                    csvFile.write(String.format("%,10f;", metrics[i+j]));
                }

                csvFile.write(System.getProperty("line.separator"));
            }

            csvFile.close();
        } catch(IOException e) {
            System.out.println(e.getMessage());
        }
    }

But I get this error:

C:\Users\Nazgulled\Documents\Workspace\Só Amigos\output\1274715228419_5000-List-ImportDatabase.csv (The system cannot find the path specified)

Any idea why?

I'm using NetBeans on Windows 7 if it matters...

Livable answered 24/5, 2010 at 15:41 Comment(4)
does that path and file exist?Spreadeagle
also minor point, it's generally good form to use Path.Combine() ...Spreadeagle
No, but as I'm trying to write and not read, I thought the path/file would be created automatically...Livable
Path.Combine probably isn't a great suggestion for Java :-).Genvieve
A
17

In general, a non existent file will be created by Java only if the parent directory exists. You should check/create the directory tree:

  String filenameFullNoPath = fileTimestamp + "_"  + fileDBSize + "-" 
        + fileName + ".csv";
  File myFile =  new File(System.getProperty("user.dir")  + File.separator 
        + "output" + File.separator + filenameFullNoPath);
  File parentDir = myFile.getParentFile();
  if(! parentDir.exists()) 
      parentDir.mkdirs(); // create parent dir and ancestors if necessary
  // FileWriter does not allow to specify charset, better use this:
  Writer w = new OutputStreamWriter(new FileOutputStream(myFile),charset);
Arreola answered 24/5, 2010 at 15:56 Comment(1)
I think you may need to replace "myFile.getParent()" (which returns a String) with "myFile.getParentFile()".Chesterfieldian
R
2

You can use getParentFile (Java Doc) to make sure that the parent directory exists. The following will check that the parent directory exists, and create it if it doesn't.

File myFile =  new File(fileName);
if(!myFile.getParentFile.exists()) {
     myFile.getParentFile.mkdirs();
}
Rodmun answered 13/12, 2013 at 5:28 Comment(0)
G
1

I'd guess that the "output" directory doesn't exist. Try adding:

new File(System.getProperty("user.dir") + File.separator + "output").mkdir();
Genvieve answered 24/5, 2010 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.