java - Scanner.hasNextLine() 方法看不到文件中的下一行

标签 java xml

我有以下代码:

Scanner scanner = new Scanner (file);
while (scanner.hasNextLine()){
     System.out.println ("Next line");
     String line = scanner.nextLine();

}

起初打印语句从未执行过。我认为这很奇怪,因为该文件是一个包含大约 2,000 行的 xml 文件。为了好玩,我尝试在初始化 Scanner 对象之前插入以下内容:

try{
    Desktop.getDesktop().open(file);
} catch (Exception e){}

当我运行程序时,文件被打开并且打印语句执行了 2,000 次(意味着 scanner.hasNextLine() 有效)。我认为这是与权限有关的问题,所以注释掉上面的代码并尝试:

file.setWritable(true);
file.setExecutable(true);
file.setReadable(true);

scanner.hasNextLine() 回到不工作状态,打印语句从未执行。我做错了什么?

更新:

整个函数如下所示:

public void addToList (File file){
    try{
        file.setWritable(true);
        file.setExecutable(true);
        file.setReadable(true);

        if (file.exists())
            System.out.println("File exists");
        Scanner scanner = new Scanner (file, "UTF-8");
        int lineCount=0;
        while (scanner.hasNextLine()){
            System.out.println("Next line");
            String line = scanner.nextLine();
        }

    }

    catch (FileNotFoundException e){
        System.err.println (e.getMessage());
    }

}

其中文件是绝对路径

最佳答案

您使用了 try,但从未捕获到任何东西,这可能是问题所在。当我添加一个 catch 并使用 xml 文件运行此代码时,它运行良好:

public static void main(String[] args) {
    addToList(new File("/Users/[YourName]/Desktop/[FileName].xml"));
}

public static void addToList (File file){
    try{
        file.setWritable(true);
        file.setExecutable(true);
        file.setReadable(true);

        if (file.exists())
            System.out.println("File exists");
        Scanner scanner = new Scanner (file, "UTF-8");
        int lineCount=0;
        while (scanner.hasNextLine()){
            System.out.println("Next line");
            String line = scanner.nextLine();
        }

    } catch (Exception e) {
        System.out.println(e);
    }
}

关于java - Scanner.hasNextLine() 方法看不到文件中的下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45202104/

相关文章:

Java - 针对白名单的手动对象验证

java - Spring aop :config

android - 组织 Strings.xml

java - beans.xml Spring CXF 中的奇怪验证错误

java - 尝试使用 ProGuard 混淆导出 apk 时出现 "Out Of Memory"

java - 为什么 java.sql.DriverManager.getConnection(...) 挂起?

java - 安卓 : Parse XML with Sax failed (goes to exception)

c# - Xml 类序列化错误

java - 按最大数对数组进行排序

java - 采访 : Find the whole cubes between range of two Integers