I am successfully writing strings to a text file with the PrintWriter, and by default the output text file is written to the directory of the Eclipse project I'm working on.
But my Eclipse project has a specific folder called Resources that I want the text file to be written to:
My code is:
protected void saveCommandsToFile() throws FileNotFoundException, IOException {
PrintWriter out = new PrintWriter("commands.txt");
int listsize = list.getModel().getSize();
for (int i=0; i<listsize; i++){
Object item = list.getModel().getElementAt(i);
String command = (String)item;
System.out.println(command); //use console output for comparison
out.println(command);
}
out.close();
}
If I change the line to:
PrintWriter out = new PrintWriter("/Resources/commands.txt");
The FileNotFoundException is being thrown. How do I get around this? Thank you!
A PrintWriter
created this way will expect a path, which can be either relative or absolute.
Relative paths are relative to the working directory.
Absolute paths on the other hand need to contain the full path from the root directory (or directories, as it happens), so on a Windows box it'll be something like c:/foo/bar.txt
, on Unix-type systems /home/nobody/foo/bar.txt
.
The exact rules on absolute and relative paths can be found here.
A note though on the use of relative paths. Be careful when you're relying on them because you have no way of knowing what your working directory is going to be: when you run your application from Eclipse, it will default to your project directory but if you package it up and run from command line, it will be somewhere else.
And even if you're only running it from Eclipse, writing in your project folder isn't the best of ideas. Not only is it possible to accidentally overwrite your source code, but your code won't be very portable, if later on you decide to package everything up in a jar file, you'll find you won't be able to find those directories any more (because they're all packaged up).
Try below code:
protected static void saveCommandsToFile() throws FileNotFoundException, IOException {
File file = new File("resources/commands.txt");
System.out.println("Absolute path:" + file.getAbsolutePath());
if (!file.exists()) {
if (file.createNewFile()) {
PrintWriter out = new PrintWriter(file);
out.println("hi");
out.close();
}
}
}
Here is the project folder structure:
Project
|
|___src
|
|___resources
|
|___commands.txt
The path you are specifying is an absolute path. If you want it to be relative to where you're running the java program try using "./Resources/commands.txt"
.
Alternative you could use the full path to the folder within your project.