ここでは、保存したファイルから行を読み取って 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 にテキストを設定する試みを削除すると、例外をキャッチすることなく、ファイルのデータがスコア変数とスコア 1 変数に適切に保存されることがわかりました。
多くのシナリオを試しましたが、すべて別の理由で失敗しました。
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 に使用することはできません。私は何を間違っていますか?