简体   繁体   English

读取输入文件Java

[英]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. 我正在尝试读取输入文件“ 1.in”,并将第一行分配给变量,第二行分配给另一个变量,依此类推。 The file is fairly short, 100 lines. 该文件很短,只有100行。 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 或者您可以使用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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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