简体   繁体   English

使用扫描仪从文本文件中读取某一行

[英]Reading a certain line from a text file using Scanner

I am reading values in a text file one by one without any problem in Java.我正在一个一个地读取文本文件中的值,在 Java 中没有任何问题。 The file has integer values as shown below:该文件具有 integer 值,如下所示:

2 3 2 3
5 6 7 8 9 5 6 7 8 9
12 13 15 18 21 26 55 12 13 15 18 21 26 55
16 24 45 58 97 16 24 45 58 97

I need to read just a single line values instead of reading all values and there is an example on How to get line number using scanner , but I am looking a solution without using LineNumberReader and using a counter by looping all lines.我只需要读取单行值而不是读取所有值,并且有一个关于如何使用扫描仪获取行号的示例,但我正在寻找一个不使用LineNumberReader并通过循环所有行来使用计数器的解决方案。 Instead, it would be good to get the line number via scanner method that I already use to read values.相反,最好通过我已经用来读取值的扫描仪方法获取行号。 Is it possible?可能吗?

Here is the method I try to create:这是我尝试创建的方法:

public static List<Integer> getInput(int lineIndex) throws FileNotFoundException{   
    List list = new ArrayList<Integer>();
    Scanner scan = new Scanner(new File(INPUT_FILE_NAME));
    int lineNum=0;
    //s = new Scanner(new BufferedReader(new FileReader("input.txt")));

    while(scan.hasNextLine()) {         
        if(lineNum == lineIndex) {
               list.add(scan.nextInt()); //but in this case I also loop all values in this line
        }
        lineNum++;      
    }
    scan.close();
    return list;
}

If you have a small file, where it is acceptable to load the whole content into memory:如果您有一个小文件,可以将整个内容加载到 memory 中:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

....

public static List<Integer> getInput(int lineIndex) {
    List<Integer> list = new ArrayList<>();
    try {
        String line = Files.readAllLines(Paths.get("path to your file")).get(lineIndex);
        list = Pattern.compile("\\s+")
                .splitAsStream(line)
                .map(Integer::parseInt)
                .collect(Collectors.toList());
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return list;
}

The method Files.readAllLines returns a list of all lines of the file as strings, where each string corresponds to one line. Files.readAllLines方法以字符串形式返回文件所有行的列表,其中每个字符串对应一行。 with get(lineIndex) you get the desired nth line back and only have to parse the strings to integers.使用get(lineIndex)您可以获得所需的第 n 行,并且只需将字符串解析为整数。

Second approach:第二种方法:

If you have a large file make use of the lazy evaluation of streams:如果您有一个大文件,请使用流的惰性评估:

public static List<Integer> getInputLargeFile(int lineIndex) {
    List<Integer> list = new ArrayList<>();
    try (Stream<String> lines = Files.lines(Paths.get("path to your file"))) {
        String line = lines.skip(lineIndex).findFirst().get();
        list = Pattern.compile("\\s+")
                .splitAsStream(line)
                .map(Integer::parseInt)
                .collect(Collectors.toList());
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return list;
}

With this approach you use the method lines.skip to jump n lines from the beginning of the file.使用这种方法,您可以使用方法lines.skip从文件开头跳转n 行。 And with findFirst().get() you get the next line after your jump.并且使用findFirst().get()可以在跳转后获得下一行。 Then do the same as above to convert the numbers.然后执行与上述相同的操作来转换数字。

Not to iterate while reading the number in desired line, maybe you can read the line with scanner.nextLine() , then you can use split("\\s") to get the staring values of integers into an array, then you can simply cast and add them in your list:在读取所需行中的数字时不要迭代,也许您可以使用scanner.nextLine()读取该行,然后您可以使用split("\\s")将整数的起始值放入数组中,然后您可以只需投射并将它们添加到您的列表中:

public static void main(String[] args) throws FileNotFoundException {
    Scanner scan = new Scanner(new File("input.txt"));
    List<Integer> list = new ArrayList<>();
    int lineNum = 0;
    int lineIndex = 2;

    while(scan.hasNextLine()) {
        if(lineNum == lineIndex) {
            String[] nums = scan.nextLine().split("\\s");
            for (String s : nums){
                list.add(Integer.parseInt(s));
            }
            break;
        }
        lineNum++;
        scan.nextLine();
    }

    System.out.println(list); // [12, 13, 15, 18, 21, 26, 55]
}

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

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