这里我只是尝试从保存的文件中读取行,然后将它们显示在 JTextArea 中。
注意:我尝试显示的 JTextArea 已经过测试并且工作正常,因此不存在问题。
try
{
File ScoreFile = new File("ScoreFile.FILE");
FileInputStream Read1 = new FileInputStream(ScoreFile);
InputStreamReader Read2 = new InputStreamReader(Read1);
BufferedReader ReadIt = new BufferedReader(Read2);
String score = ReadIt.readLine();
String score1 = ReadIt.readLine();
GraphicGameBoard.topScoreDisplay.setText(score + "\n");
GraphicGameBoard.topScoreDisplay.setText(score1 + "\n");
ReadIt.close();
Read2.close();
Read1.close();
}
catch (Exception X) { System.out.print("Oops, Can't Load.");}
这每次都会捕获异常。我已经确定,如果我删除在 topScoreDisplay 中设置文本的尝试,它会将文件中的数据正确保存到 Score 和 Score1 变量中,而不会捕获异常。
我尝试了很多方案,但它们都因不同的原因而失败。
1:此操作失败,因为 Score 和 Score1 尚未在 try/catch 外部初始化,但在 try/catch 内部,变量成功存储了 System.out.print 显示的数据。如果我将 System.out.print 移到 try/catch 之外,那么它将不会打印。
try
{
File ScoreFile = new File("ScoreFile.FILE");
FileInputStream Read1 = new FileInputStream(ScoreFile);
InputStreamReader Read2 = new InputStreamReader(Read1);
BufferedReader ReadIt = new BufferedReader(Read2);
String score = ReadIt.readLine();
String score1 = ReadIt.readLine();
System.out.print(score + "\n" + score1 + "\n");
ReadIt.close();
Read2.close();
Read1.close();
}
catch (Exception X) { System.out.print("Oops, Can't Load.");}
GraphicGameBoard.topScoreDisplay.setText(score + "\n");
GraphicGameBoard.topScoreDisplay.setText(score1 + "\n");
2:如果我在 try/catch 之前初始化变量,则 System.out.print 将使用 try/catch 内部或外部的正确信息。如果 .setText 在里面,它将捕获异常。如果它在外部,则会导致 NPE。
String score;
String score1;
try
{
File ScoreFile = new File("ScoreFile.FILE");
FileInputStream Read1 = new FileInputStream(ScoreFile);
InputStreamReader Read2 = new InputStreamReader(Read1);
BufferedReader ReadIt = new BufferedReader(Read2);
score = ReadIt.readLine();
score1 = ReadIt.readLine();
System.out.print(score + "\n" + score1 + "\n");
ReadIt.close();
Read2.close();
Read1.close();
}
catch (Exception X) { System.out.print("Oops, Can't Load.");}
GraphicGameBoard.topScoreDisplay.setText(score + "\n");
GraphicGameBoard.topScoreDisplay.setText(score1 + "\n");
因此,我可以将文件数据保存到变量中,并且可以使用 System.out.print 来显示它。但我不能使用变量 .setText。我做错了什么?
最佳答案
你没有说异常是什么X.printStackTrace();
是你的 friend 找出来的。
我猜测这是因为您试图从非 UI 线程更改 UI。
要解决这个问题,您需要执行以下操作:
final String score = ReadIt.readLine();
final String score1 = ReadIt.readLine();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GraphicGameBoard.topScoreDisplay.setText(score + "\n");
GraphicGameBoard.topScoreDisplay.setText(score1 + "\n");
}
});
最好使用finally block 关闭流。
因此,在创建每个流后尝试{
,然后在完成后}最后{stream.close();}
。这样做的原因是,无论出现什么问题,您都会清理正在使用的资源。
您可能想这样读取循环中的行:
final StringBuilder sb = new StringBuilder();
for (String line = readIt.nextLine(); line != null; line = readIt.nextLine()) {
sb.append(line);
sb.append("\n");
}
GraphicGameBoard.topScoreDisplay.setText(sb.toString());
关于java - 从文件读取数据并将其显示在 JTextArea 中时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18218904/