2015-09-30 78 views
-4

StackOverflow的第一个问题,所以如果这是不好的道歉。但我为土木工程师找到了一份学生工作计划。我的第一个任务是使用JFileChooser来允许用户指定所需的文件,然后将此文件的完整路径写入txt文件。我希望它自动写入使用JFileChooser的程序所在的文件。我很困惑如何做到这一点,一直没有找到有用的东西。文件I/O混淆

我的代码:

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); 
     } 
    } 
} 
+1

为了让回答者或其他有类似问题的人更容易,请编辑添加一个特定的问题陈述 - “不起作用”可以假设,但* how *不起作用?什么错误信息或不正确的行为是特征? –

回答

1

那么究竟是什么问题,你实际上有?

注释:

file_chooser.setCurrentDirectory(new java.io.File("user.home")); 

这不会把当前目录是用户的主目录。但是到当前目录中名为“user.home”的目录(如果存在)。什么你可能想要做的是:

file_chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home"))); 

更新通过阅读这个回答您的评论:

你已经在你的变量path的绝对路径。但是使用构造函数new File(user_home_folder, path)将它与用户主目录的位置一起加上前缀。这样会产生一个像这样的路径,例如驱动器盘符有两次。删除此构造函数的第一个参数。

+0

好吧,那移动FileChooser对象到正确的目录。但它仍然在该行抛出FileNotFoundException:BufferedWriter path_writer = new BufferedWriter(new FileWriter(path_file)); – MrPeanutButter

+0

@theo_the_NOVICE您之前的评论更有帮助。 FileNotFoundException的消息告诉你无法找到哪个文件。由于该文件的路径不正确,找不到该文件。 (正如我在更新中解释的答案。) –

+0

好的,谢谢你对模糊还在学习如何提问很抱歉。它现在执行得很好,谢谢! – MrPeanutButter