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

不羁岁月 提交于 2019-12-13 01:29:08

问题


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


来源:https://stackoverflow.com/questions/15239053/using-a-printwriter-and-file-object-to-write-to-an-output-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!