我做了一个GUI和一个按钮。
我的代码如下所示:
private void jButtonSubmitActionPerformed(java.awt.event.ActionEvent evt) {
try {
Scanner scan = new Scanner(new File("persontest.txt"));
while(scan.hasNext()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException ex) {
System.out.println("File not found" + ex.getMessage());
} catch (Exception e) {
System.out.println("Some error" + e.getMessage());
}
persontest.txt 包含以下文本:
- 在团队合作中,我有什么贡献:
一个。我提出了新的想法
b.我跟进事情,因为我基本上 彻底
c.我评估什么是现实和可行的
d.我主张客观公正地提出替代方法
尝试运行时出现"一些错误未找到行"
我尝试从文本中删除所有特殊字符,我可以阅读它,所以我尝试以这种方式将"UTF-8"添加到扫描仪中。
Scanner scan = new Scanner(new File("persontest.txt"), "UTF-8");
然而,这似乎没有任何作用。我仍然得到"找不到行"。
如果这个问题之前有人问过,对不起,我做了彻底的搜索,但我要么无法理解所提出的问题,要么无法理解在我的问题的上下文中提供的答案。
我根据故障排除和哈沙斯示例将扫描仪更改为缓冲阅读器,现在即使使用特殊字符,它也会读取文本,但它不会正确显示它们。我只是得到方框。这是一个小问题。
如果 persontest.txt 位于类路径中(即在 jar 或源文件夹中),您可以使用:
YourClass.class.getClassloader().getResourceAsStream("persontest.txt")
,确保persontest.txt位于您的主项目文件夹中,而不是该文件夹的子文件夹中,否则它将无法找到它。
我建议使用缓冲阅读器逐行读取它。方法如下:
BufferedReader input = new BufferedReader(new FileReader("persontest.txt"));
String line;
while ((line = input.readLine()) != null && !line.isEmpty()) {
System.out.println(line);
}
最好检查该行是否不为空,同时检查它是否等于 null。例如,如果一行等于 \t,则将其归类为空,但不分类为 null。
你可以简单地使用
try {
String line;
BufferedReader br = new BufferedReader(new FileReader("persontest.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
如果您需要使用扫描仪进行操作,可以尝试使用
Scanner reader = new Scanner(new FileInputStream("persontest.txt");