使用 Java 读取文件时无法获取文件的最后一行

问题描述 投票:0回答:0

我正在尝试读取文件

input.txt
但我的
while()
循环似乎在读取文件时以无限状态结束。我该如何解决这个问题?我使用的代码是这样的:

    import java.util.Scanner;
    import java.io.File;
    import java.io.FileNotFoundException;
    
    
    public class Read {
        public static void main(String[] args) {
            try {
                File script = new File("input.txt");
                Scanner sc = new Scanner(script);
                int cnt = 0;
    
                while(sc.hasNextLine()) {
                    cnt++;
                }
    
                System.out.println("Your doucument has " + cnt + " line(s).");
                sc.close();
    
            } catch(FileNotFoundException e) {
                System.out.println("File with the same name not found");
    
            }
        }    
    }
java exception file-read java-17
© www.soinside.com 2019 - 2024. All rights reserved.