我尝试了多种方法来打开一个文本文件,我的程序使用该文件在 map 创建器中显示 map 。一切正常,除了如果我选择一个文本文件,我会得到“null”作为字符串。我不知道它是如何变为空的,因为该文件存在(并且我在加载它之前检查了它)
这是我两次尝试的 2 个代码块:
public String OpenText(){
String str = null;
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
System.out.println("Opening: " + file.getName() + ". " + "Path: "+file.getPath());
if(new File(file.getPath()).exists()){
try {
System.out.println("File Exists.");
/*FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
while((str = br.readLine())!= null){
sb.append(str);
}
*/
StringBuilder sb = new StringBuilder();
Scanner input = new Scanner(file);
while(input.hasNext()){
sb.append(input.nextLine());
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
System.out.println("Open command cancelled by user.");
}
System.out.println(str);
return str;
}
代码在第一次尝试和第二次尝试时都给出“null”作为返回。
我知道第一个代码可以工作,因为我用它来保存我的设置。但我也用扫描仪尝试过。
额外信息:我尝试打开的文件中有文本。我尝试了不同的文本文件。
最佳答案
我正在关注您的案例。
我尝试如下,它适用于文本文件(txt)
StringBuilder sb = new StringBuilder();
Scanner input = new Scanner(file);
while(input.hasNext()){
sb.append(input.nextLine());
sb.append("\n");
}
str = sb.toString(); <-- Did you miss it?
关于java - Java 中的 OpenFile 对话框给出 null 作为响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23190608/