Jonathan
Jonathan

Reputation: 599

Using a PrintWriter and File Object to Write to an Output File

I have a JFileChooser object used to get a data file from the user. What I need to do is create a File object and PrintWriter object so that I can write to a file named "output.txt". The file should be written to the same directory from which the data file was retrieved from.

So far I have tried:

// Write to a text file`

File file = new File ("output.txt");
PrintWriter printWriter = new PrintWriter (f);

This snippet of code creates the output file, but I need to it be written to the same directory from which the data file came from.

First thoughts were to call the .getPath() method (see below) on the JFileChooser object.

String fileDir = inputFile.getPath();
String fileName = "output.txt";
File f = new File (fileDir + "/" + fileName);
PrintWriter printWriter = new PrintWriter (f);

Thoughts?

Upvotes: 1

Views: 6570

Answers (1)

dlock
dlock

Reputation: 9577

inputFile.getPath() will get you the file path. You need inputFile.getParent() which will get you the directory of the file.

String fileDir = inputFile.getParent(); 
String fileName = "output.txt";
File f = new File (fileDir,fileName);
PrintWriter printWriter = new PrintWriter (f);

Upvotes: 4

Related Questions