1
    open.addActionListener(new ActionListener(){
        public void actionPerformed (ActionEvent e){
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(new java.io.File("."));
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
                System.out.println(fileChooser.getSelectedFile());
                }
        }
    });

这可能是一个措辞不好的问题,但我们开始:

我需要这部分代码来生成'fileChooser.getSelectedFile());' 以可以在其他地方使用的格式。我不介意它是否是一个变量(不会真正起作用,因为我需要在另一个 actionListener 中调用它)或(按照我的计划)将所选文件夹作为字符串输出到输出文件,然后在其他地方读取该文件在节目中。

文件路径(例如 C:/Users/Desktop/)是一个字符串很重要,因为这是将使用该路径的类所接受的内容。

我尝试了几个选项,但经常遇到“不可转换类型”编译错误等,如果有人有任何想法可以分享,那就太好了

4

3 回答 3

2

JFileChoose.getSelectedFile() 返回一个 File 对象,而不是 String 对象。

File 对象具有 getAbsolutePath()、getPath()、getName()、getParent() 等方法,它们返回文件名和路径的字符串版本。

所以像:

File file = fileChooser.getSelectedFile();
System.out.println("Selected file is: "+file.getAbsolutePath()+"/"+file.getName());

应该得到你想要的。

另外仅供参考,这不会编译...

String exportPath = fileChooser.getSelectedFile();

...因为 getSelectedFile() 返回的 File 对象不是 String 对象。但是,File 对象(与所有对象一样)有一个 toString() 方法,当您执行此操作时会自动调用该方法来构建字符串......

String exportPath = fileChooser.getSelectedFile() +"\\";

正如我所说,优雅的方式是这样的:

String exportPath = fileChooser.getSelectedFile().getAbsolutePath();

希望这有帮助,祝你好运!抢

于 2011-02-13T14:53:33.400 回答
1
open.addActionListener(new ActionListener(){
        public void actionPerformed (ActionEvent e){
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(new java.io.File("."));
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
                try{
                DataOutputStream outputPath = new DataOutputStream(new FileOutputStream("C:/Users/Jonathan/Desktop/YouDetectJava/FolderPath.dat"));
                String exportPath = fileChooser.getSelectedFile() + "\\";
                outputPath.writeUTF(exportPath);
                //System.out.println(exportPath);
                }catch (IOException ioe){
                }
                }
        }
    });

似乎可以修复它。很抱歉发布并回答我自己的问题。在我等待回复的时候想出了如何去做。似乎是一个字符串'exportPath'必须有一个字符串。在这种情况下,“\”但也可以是“”。

不知道为什么,但你去了:D

于 2011-02-13T14:40:00.363 回答
1

这样做的可能性很小:

// just path as a String
fileChooser.getSelectedFile().getPath();
// the same, this is done implicitly in your answer
fileChooser.getSelectedFile().toString();
// absolute path, if you need it
fileChooser.getSelectedFile().getAbsolutePath();
// canonical path, not sure what that is
fileChooser.getSelectedFile().getCanonicalPath();
于 2011-02-13T14:53:05.727 回答