简体   繁体   中英

Java: How to scan from a user specified file

More specifically, how could I write code that could create a scanner for any text file that the user enters? For instance, one user might want to scan text from "foo.txt," and another might want to read from "bar.txt." How do I compensate for this?

You can simply make a function that opens a file and returns the reader so that you can read each line:

public BufferedReader readFromFile(String path) {
    try {
        return new BufferedReader(new FileReader(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then use the BufferedReader which it returns and iterate through each line! Hope it helps!

You can take the path to the file as an input to the program. For taking input, you can have a look at http://www.programmingsimplified.com/java/source-code/java-program-take-input-from-user

Once you have this path in a variable, you can replace the hardcoded file names by this variable instead.

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