简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM