繁体   English   中英

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

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

我正在一个一个地读取文本文件中的值,在 Java 中没有任何问题。 该文件具有 integer 值,如下所示:

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

我只需要读取单行值而不是读取所有值,并且有一个关于如何使用扫描仪获取行号的示例,但我正在寻找一个不使用LineNumberReader并通过循环所有行来使用计数器的解决方案。 相反,最好通过我已经用来读取值的扫描仪方法获取行号。 可能吗?

这是我尝试创建的方法:

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;
}

如果您有一个小文件,可以将整个内容加载到 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;
}

Files.readAllLines方法以字符串形式返回文件所有行的列表,其中每个字符串对应一行。 使用get(lineIndex)您可以获得所需的第 n 行,并且只需将字符串解析为整数。

第二种方法:

如果您有一个大文件,请使用流的惰性评估:

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;
}

使用这种方法,您可以使用方法lines.skip从文件开头跳转n 行。 并且使用findFirst().get()可以在跳转后获得下一行。 然后执行与上述相同的操作来转换数字。

在读取所需行中的数字时不要迭代,也许您可以使用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