gpt4 book ai didi

java - 文件未找到异常错误

转载 作者:行者123 更新时间:2023-12-01 10:03:11 25 4
gpt4 key购买 nike

大家好,我是 java 新手,我遇到了一些麻烦,为什么我收到文件未找到异常。我只是想让用户使用 jfilechooser 打开文件,然后将一行文本打印到选项 Pane 消息中。关于什么是错误的/什么需要修复有什么想法吗?谢谢

package synchro;

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class SynchroTest {
public static void main(String[] args){
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());

try{
Scanner input = new Scanner(new File(selectedFile.getName()));
while(input.hasNext()){
String line = input.nextLine();
JOptionPane.showMessageDialog(null, "Input sentence:\n" + line);
}

}catch(FileNotFoundException e){
System.out.println("File Not Found");
}
}
}
}

最佳答案

我不明白你为什么要循环。

File selectedFile = fileChooser.getSelectedFile(); 为您提供 File所单击的文件的对象。

只需使用 Scanner input = new Scanner(selectedFile); 即可解析文件。

while( input.hasNext() ) {
String line = input.nextLine();
System.out.println(line);
}

关于java - 文件未找到异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36658501/

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