我正在为扫雷器编写GUI,并将此困难保存在文本文件中。但是,它始终没有清空文件,而是总是清空文件并触发我的空检查条件。
我尝试使用调试并手动编辑文本文件以包含字符串“ HARD”,但是在更改了难度(将其再次设置为hard或切换为easy)之后,文件变为空。
public class MineSweeperMain extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
String difficulty;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("LastProgramState.txt"));
difficulty = br.readLine();
if (difficulty == null) {
System.out.println("???");
throw new FileNotFoundException(); // If I comment this out, file becomes empty
}
} catch (FileNotFoundException e) {
BufferedWriter bw = new BufferedWriter(new FileWriter("LastProgramState.txt"));
bw.write("EASY");
bw.close();
difficulty = "EASY";
} finally {
if (br != null)
br.close();
}
int xSize;
int ySize;
int bombCount;
System.out.println(difficulty);
if (difficulty == null) {
System.exit(200);
}
if (difficulty.equals("HARD")) {
xSize = 16;
ySize = 16;
bombCount = 40;
}
else {
xSize = 9;
ySize = 9;
bombCount = 10;
}
Menu menu1 = new Menu("Options");
Menu menu2 = new Menu("Help");
MenuItem mi1 = new MenuItem("Difficulty: Easy");
MenuItem mi2 = new MenuItem("Difficulty: Hard");
MenuItem mi3 = new MenuItem("How to play");
MenuItem mi4 = new MenuItem("About...");
menu1.getItems().add(mi1);
menu1.getItems().add(mi2);
menu2.getItems().add(mi3);
menu2.getItems().add(mi4);
MenuBar bar = new MenuBar();
bar.getMenus().addAll(menu1,menu2);
Label score = new Label("Score:");
Scene scene = new Scene(bp);
primaryStage.setScene(scene);
primaryStage.setTitle("MineSweeper");
primaryStage.show();
}
mi1.setOnAction(event -> { //EASY
try {
BufferedWriter bwriter = new BufferedWriter(new FileWriter("LastProgramState.txt"));
bwriter.write("EASY");
} catch (IOException e) {
System.exit(100);
}
primaryStage.close();
Platform.runLater( () -> { //RUN APPLICATION AGAIN
try {
new MineSweeperMain().start( new Stage() );
} catch (Exception ex) {
System.exit(100);
}
} );
});
mi2.setOnAction(event -> { //HARD
try {
BufferedWriter bwriter = new BufferedWriter(new FileWriter("LastProgramState.txt"));
bwriter.write("HARD");
} catch (IOException e) {
System.exit(100);
}
primaryStage.close();
Platform.runLater( () -> {
try {
new MineSweeperMain().start( new Stage() );
} catch (Exception ex) {
System.exit(100);
}
} );
});
}
如果我选择困难,则我希望txt文件包含字符串“ HARD”,但它包含字符串“ EASY”。当我选择轻松难度时,也会发生相同的行为。我还注意到,如果我删除了抛出新的FileNotFoundException()的文件,则该文件将完全为空。我究竟做错了什么?任何帮助表示赞赏。
编辑:问题已解决,在mi1.setOnAction()
和mi2.setOnAction()
中写入in后,我忘了关闭文件。