Unfitacorn Unfitacorn - 2 months ago 15
Java Question

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

I'm trying to return the file selected by the user. That works fine. I can check fileToOpen in openFile and it is 100% correct, but when I sysout it in the main method I just get null. I want the path that the user has selected.

This is the main class:

public class Main {

public static void main(String[] args) {

File fileToOpen = null;

ReadIn openLog = new ReadIn();

openLog.openFile(fileToOpen);

System.out.println(fileToOpen);

}
}


This is the ReadIn 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;

}

}

Answer

Your code is expecting the openFile method to be able to reach into the calling method and modify one of its local variables. It can't do that, it's not a feature Java has1 (and not a useful way to solve this problem).

Your method already returns the File. Just remove the argument and make it a local variable:

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;

}

And then when using it, use the return value:

public static void main(String[] args) {

    File fileToOpen = null;

    ReadIn openLog = new ReadIn();

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

    System.out.println(fileToOpen);

}

1 The feature is called "pass-by-reference," if you're interested, which means "passing a reference to a variable into a method/function." Java never does that, it always passes the value of variables into methods (and method-like things such as constructors) ("pass-by-value"). More: Is Java "pass-by-reference" or "pass-by-value"?