使用PrintWriter和文件对象写入输出文件 [英] Using a PrintWriter and File Object to Write to an Output File

查看:476
本文介绍了使用PrintWriter和文件对象写入输出文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JFileChooser 对象,用于从用户获取数据文件。我需要做的是创建一个文件对象和 PrintWriter 对象,以便我可以写入名为output.txt的文件。该文件应该被写入到从中检索数据文件的同一个目录。

到目前为止,我已经尝试过了:

  //写入文本文件`

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

这段代码创建了输出文件,但是我需要将它写入同一个目录数据文件来自哪里。



第一个想法是在JFileChooser对象上调用.getPath()方法(见下面)。

 字符串fileDir = inputFile.getPath(); 
String fileName =output.txt;
文件f =新文件(fileDir +/+ fileName);
PrintWriter printWriter = new PrintWriter(f);

想法?

解决方案

inputFile.getPath()会为您提供文件路径。您需要 inputFile.getParent()这将得到您的文件的目录。

  String fileDir = inputFile.getParent(); 
String fileName =output.txt;
文件f =新文件(fileDir,fileName);
PrintWriter printWriter = new PrintWriter(f);


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

这篇关于使用PrintWriter和文件对象写入输出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆