如何 return 来自不同 class 的文件?只有 returning null

How to return a File from a different class? Only returning null

我正在尝试 return 用户选择的文件。那很好用。我可以在 openFile 中检查 fileToOpen,它是 100% 正确的,但是当我在 main 方法中对其进行系统输出时,我只是得到 null。我想要用户选择的路径。

这是主要的class:

    public class Main {

    public static void main(String[] args) {

        File fileToOpen = null;

        ReadIn openLog = new ReadIn();

        openLog.openFile(fileToOpen);

        System.out.println(fileToOpen);

    }
}

这是读入 class:

public class ReadIn extends JFrame{


    public File openFile(File fileToOpen){

        final JFileChooser fileChooser = new JFileChooser();
        int modalToComponent=fileChooser.showOpenDialog(this);
        if (modalToComponent == JFileChooser.APPROVE_OPTION) {
            fileToOpen = fileChooser.getSelectedFile();         
        }

        return fileToOpen;

    }

}

您的代码期望 openFile 方法能够进入调用方法并修改其局部变量之一。它不能那样做,它不是 Java 具有 1 的功能(也不是解决此问题的有用方法)。

您的方法已经 return 成为 File。只需删除参数并将其设为局部变量即可:

public File openFile(/*no argument here*/){
    File fileToOpen; // Local variable

    final JFileChooser fileChooser = new JFileChooser();
    int modalToComponent=fileChooser.showOpenDialog(this);
    if (modalToComponent == JFileChooser.APPROVE_OPTION) {
        fileToOpen = fileChooser.getSelectedFile();         
    }

    return fileToOpen;

}

然后在使用的时候,使用return值:

public static void main(String[] args) {

    File fileToOpen = null;

    ReadIn openLog = new ReadIn();

    fileToOpen = openLog.openFile();    // ***

    System.out.println(fileToOpen);

}

1 如果您感兴趣,该功能称为 "pass-by-reference,",这意味着 "passing a reference to a variable into a method/function." Java 永远不会那样做,它总是通过将变量的 value 转换为方法(以及类似方法的东西,例如构造函数)("pass-by-value")。更多:Is Java "pass-by-reference" or "pass-by-value"?