Beginner
Beginner

Reputation: 143

Accessing a file in a different Java class?

I retrieved a file using the JFileChooser in the main method of my java program. My question is how do I access this file in a different class within the same package of my program?

Upvotes: 1

Views: 638

Answers (1)

Jakub
Jakub

Reputation: 3129

Classes can communicate in different ways and choosing the right way depends on the specific case and the architecture. I would go with saving the file into a field in your class and create a getter for that field. Thanks to that you will be able to access the file in other classes.

So your classes could look something like that:

public class FileHolder {

    private File file;

    public File getFile() {
        return this.file;
    }

    private void retrieveFile() {
        // method which sets the file
    }

    // other methods and fields

 }

and

public class FileUser {

   private void doSomethingWithTheFile() {
        FileHolder fileHolder = new FileHolder();
        fileHolder.retrieveFile();
        File file = fileHolder.getFile();
        // use the file
    }

}

Upvotes: 2

Related Questions