Inglonias
Inglonias

Reputation: 532

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

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?

Upvotes: 9

Views: 38404

Answers (3)

Dror
Dror

Reputation: 1

It should be created as a sibling of the file pointed by filePath.

for example if

File filePath = new File("C:\\\\Test\\\\a.txt");

Then it should be created under Test dir.

Upvotes: 0

Wormbo
Wormbo

Reputation: 4992

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

Upvotes: 6

Óscar López
Óscar López

Reputation: 236034

What's the value of filePath.getParentFile()? What operating system are you using? It might be a better idea to join both paths in a system-independent way, like this:

filePath.getParentFile() + File.separator + "Decrypted.txt"

Upvotes: 2

Related Questions