如何通过Gui从用户获取文件名和目录

时间:2014-08-12 18:50:59

标签: java

我想获取文件名和目录,以便使用Gui保存用户的文件,就像我们使用JFileChooser选择文件一样,请告诉我该怎么做???

3 个答案:

答案 0 :(得分:1)

我不确定你真正在问什么,但这有帮助吗?

public static File chooseDirectory(final Component parent, final String commitButtonText, final String commitTooltipString, final String chooserWindowTitle) {

    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int selection = chooser.showOpenDialog(parent);
    if (selection != JFileChooser.APPROVE_OPTION) {
        return null;
    }

    /*
     * Ok, the user has selected a folder.
     */
    return new File(chooser.getCurrentDirectory(), chooser.getSelectedFile().getName());
}

答案 1 :(得分:1)

documentation提供了一个很好的演示如何使用fileChoosers。以下是文档顶部的代码,适用于您的问题(特别是保存)

JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(); //Actually shows the chooser
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
   System.out.println("The path of this file is: " + 
        chooser.getSelectedFile().getAbsolutePath());
   System.out.println("Writing...");
   try(FileWriter fw = new FileWriter(chooser.getSelectedFile()+".txt"))
   {
     fw.write("yourfilename".toString());
   } 
}

答案 2 :(得分:0)

实际回答你的问题。获取文件名和目录可以使用以下语句完成:

myTextField.setText(myFileChooser.getSelectedFile().getAbsolutePath());

至于保存文件,只需将文件写入某个给定的文件名即可。

 try(FileWriter fw = new FileWriter(myFileChooser.getSelectedFile()+".txt"))
 {
     fw.write("yourfilename".toString());
 }
相关问题