Java 文件I/O混淆
关于StackOverflow的第一个问题,如果这是个坏问题,请道歉。但我得到了一份为土木工程师编程的学生工作。我的第一个任务是使用JFileChooser允许用户指定所需的文件,然后将该文件的完整路径写入txt文件。我希望它使用JFileChooser自动写入该程序所在的文件。我很困惑如何做到这一点,并没有找到任何有帮助的 我的代码:Java 文件I/O混淆,java,file-io,Java,File Io,关于StackOverflow的第一个问题,如果这是个坏问题,请道歉。但我得到了一份为土木工程师编程的学生工作。我的第一个任务是使用JFileChooser允许用户指定所需的文件,然后将该文件的完整路径写入txt文件。我希望它使用JFileChooser自动写入该程序所在的文件。我很困惑如何做到这一点,并没有找到任何有帮助的 我的代码: public class FilePathFinder { JFileChooser fileChooser; String path;
public class FilePathFinder {
JFileChooser fileChooser;
String path;
public static void main(String[] args) throws IOException{
String path = null; //String that will be outputted to
//creates file chooser and its properties
JFileChooser file_chooser = new JFileChooser();
file_chooser.setCurrentDirectory(new java.io.File("user.home"));
file_chooser.setDialogTitle("Create File Path");
file_chooser.setApproveButtonText("Create Path");
file_chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
file_chooser.setAcceptAllFileFilterUsed(false);
if (file_chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION){
path=(file_chooser.getSelectedFile().getAbsolutePath());
}
//Writes path name to file
String user_home_folder = System.getProperty("user.home");
System.out.println(user_home_folder);
File path_file = new File(user_home_folder, path);
BufferedWriter path_writer = new BufferedWriter(new FileWriter(path_file));
if(!path_file.exists()){
path_writer.write(path);
}
}
}
那么,你实际遇到的问题是什么 评论:
file_chooser.setCurrentDirectory(new java.io.File("user.home"));
这不会将当前目录设置为用户主目录。但是,如果当前目录中存在名为user.home的目录,则将其复制到该目录。您可能想做的是:
file_chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home")));
通过阅读您对此答案的评论进行更新:
变量路径中已经有绝对路径。但是使用构造器newfileuser\u home\u文件夹,在路径前面加上用户主目录的位置。这将导致这样的路径,例如,其中包含两个驱动器号。删除此构造函数的第一个参数。Ok,它将FileChooser对象移动到了正确的目录。但它仍然在以下行抛出FileNotFoundException:BufferedWriter路径\ U writer=new BufferedWriternew FileWriterpath\ U文件@theo_新手您之前的评论更有帮助。FileNotFoundException的消息告诉您找不到哪个文件。找不到此文件,因为该文件的路径不正确。正如我在最新答案中所解释的。好的,谢谢你,很抱歉你的含糊不清,仍然在学习如何提问。现在很好,谢谢!为了让回答者或其他有类似问题的人更容易回答,请添加一个特定的问题陈述-可以假设它不起作用,但它如何不起作用?什么错误信息或错误行为是特征?