在这里,我只是尝试从保存的文件中读取行,然后将它们显示在 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。我究竟做错了什么?