简体   繁体   English

使用PrintWriter和文件对象写入输出文件

[英]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. 我有一个JFileChooser对象用于从用户获取数据文件。 What I need to do is create a File object and PrintWriter object so that I can write to a file named "output.txt" . 我需要做的是创建一个File对象和PrintWriter对象,以便我可以写入名为“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. 首先想到的是在JFileChooser对象上调用.getPath()方法(见下文)。

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. inputFile.getPath()将获取文件路径。 You need inputFile.getParent() which will get you the directory of the file. 你需要inputFile.getParent()来获取文件的目录。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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