java.io.IOException: The system cannot find the path specified writing a textfile

Inglonias picture Inglonias · May 27, 2012 · Viewed 27.4k times · Source

I'm writing a program where I'm trying to create a new text file in the current directory, and then write a string to it. However, when trying to create the file, this block of code:

//Create the output text file.
File outputText = new File(filePath.getParentFile() + "\\Decrypted.txt");
try
{
    outputText.createNewFile();
}
catch (IOException e)
{
    e.printStackTrace();
}

is giving me this error message:

java.io.IOException: The system cannot find the path specified
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(Unknown Source)
    at code.Crypto.decrypt(Crypto.java:55)
    at code.Crypto.main(Crypto.java:27)

Because of this I cannot write to the file because it naturally does not exist. What am I doing wrong here?

Answer

Wormbo picture Wormbo · May 27, 2012

If you're working with the File class already, consider using its full potential instead of doing half the work on your own:

File outputText = new File(filePath.getParentFile(), "Decrypted.txt");