gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:27:41 24 4
gpt4 key购买 nike

我有以下代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com