简体   繁体   中英

How can I pass a filename String to another Class so that it creates a File object in that class?

I have a file object created in a class called ReadFiles.

public class ReadFiles {
    File file = new File("google.csv");
}

When entered as above with a set "google.csv" the File creation works.

What I want to do is pass a String filename from another class StockBuySell such that it creates the File in ReadFiles is created based on the String filename. Here is what I tried:

public class ReadFiles {

    String filename;

    public ReadFiles(String filename) {
        this.filename = filename;
    }

    File file = new File(filename);
}

In the other class in the same package:

public class StockBuySell {
    ReadFiles googleData = new ReadFiles("google.csv");
}

I am given a NullPointerException. I believe that is because the file is not created by my method. What can I do? Thank you for your help.

Edit: I realized I was running into errors because of other methods related to reading the files. I ended up using hata's method to create a File. Thank you guys!

Is what you want to achieve like this?:

public class ReadFiles {

    File file;
    
    public ReadFiles(String filename) {
        file = new File(filename);
    }
}

The reason for your NullPointerException should be the field File file = new File(filename); . The filename is initially null before the Constructor method is called.

The order of initialization is a bit wonky; first all 'instance initializers' run (and expressions assigned to fields are part of this), and only then the constructor runs. Thus:

public class ReadFiles {
    private final String filename;
    private final File file;

    public ReadFiles(String name) {
         this.filename = filename;
         this.file = new File(filename); // put it here.
    }
}

There's all sorts of problems with this code, though. It's using old API, and it's got improper naming. (This code is reading 1 file, and yet is named 'ReadFiles'. Also, classes should not be named with a verb, it should describe what it represents, not what it does. It also has an additional, mostly useless field.

Fixing all that:

public class CsvReader {
    private final Path file;

    public CsvReader(String path) {
        this.file = Paths.get(path);
    }

    public CsvReader(Path path) {
        this.path = path;
    }
}

and then we run into yet another problem: reading csvs sounds simple but it isn't. Use a library such as OpenCSV .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM