简体   繁体   中英

Read input file java

I am fairly new to programming, so bear with me.

I am trying to read an input file, "1.in" and assign the first line to a variable, the second to another variable, and so on. The file is fairly short, 100 lines. How do I go about doing this? I tried researching it on the internet, but i didn't really understand the results. The only type of input i know right now is by using the scanner class, but that requires manual input.

Use some data structure to hold your data.
If you know size of your file, array is the best option. Or you can use LinkedList, ArrayList
For Example

LinkedList<String> list = new LinkedList<>();
File file = new File("data.txt");

    try {

        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            list.add(line);
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

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