文件I / O混乱

时间:2015-09-30 23:26:28

标签: java file-io

关于StackOverflow的第一个问题,如果这很糟糕,请道歉。但我为土木工程师准备了一份学生工作计划。我的第一个任务是使用JFileChooser来允许用户指定所需的文件,然后将该文件的完整路径写入txt文件。我希望它自动写入使用JFileChooser的程序所在的文件。我对如何执行此操作非常困惑,并且无法找到任何有用的信息。

我的代码:

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 个答案:

答案 0 :(得分: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)将前缀添加到用户主目录的位置。这导致像这样的路径具有两次驱动器号。删除此构造函数的第一个参数。

相关问题