【问题标题】:FileReader not reading entire text fileFileReader 没有读取整个文本文件
【发布时间】:2021-04-09 07:50:33
【问题描述】:

我希望我的代码读取一个 txt 文件并打印出每一行,但几乎一半的行被跳过似乎是随机的。如何确保读取整个文件?

        BufferedInputStream readIt = new BufferedInputStream(new FileInputStream(pBase));
        //pBase is txt File object
        Scanner actualRead = new Scanner(readIt);

    
        while(actualRead.hasNextLine()){
            System.out.println("Line is : " + actualRead.nextLine());
            
        }

【问题讨论】:

    标签: java input inputstream filereader txt


    【解决方案1】:

    最简单的方法是使用其中一种 nio 实用方法,例如readAllLines。

    对于不想一次全部加载到内存中的大文件,可以使用lines 方法,如下所示:

    import java.nio.file.Files;
    import java.nio.file.Path;
    ...
    try (var lines = Files.lines(Paths.get(pBase))) {
      lines.forEach(l -> {
        System.out.println(l);
      });
    }
    

    【讨论】:

      【解决方案2】:

      或者..scanner 可以将文件参数作为输入...

      
      Scanner actualRead = new Scanner(pBase); //directly pass the file as argument...
      //Although this threatens to throw an IOException..catch  it in try-catch or add to throws...
      try {
        Scanner actualRead = new Scanner(pBase);
        while (actualRead.hasNextLine()) {
          System.out.println("Line is : " + actualRead.nextLine());
      }
      catch (IOException e) {
        System.out.println("err...");
          
      

      【讨论】:

        猜你喜欢
        • 2016-10-15
        • 2012-09-04
        • 2019-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-02
        • 1970-01-01
        • 2017-10-01
        相关资源
        最近更新 更多