Using a PrintWriter and File Object to Write to an

2019-08-04 02:17发布

问题:

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?

回答1:

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