如何在 javafx 中捕获 IOException

How to catch IOException in javafx

我正在尝试通过按 JavaFx 中的按钮将数据写入文本文件。然而,唯一的问题是当我尝试在我的按钮处理方法中使用语句 "throws IOException" 时,事情似乎不起作用。这是我的代码。

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.control.Button;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;

public class testingFx extends Application{
//Create controls
private Button write;
private Scene main;
private Button Exit;
private Scene sceneMain; 
private File records;
private FileWriter fw;

public static void main(String[] args){
   launch(args);
 }

@Override

public void start(Stage stage) throws IOException{

  //Create new file
  records = new File("records.txt");
  records.createNewFile();
  //Create FileWriter
  fw = new FileWriter(records);

  //Create root, format controls, scene, etc...
  Group root = new Group();
  write = new Button();
  write.setText("Write");
  write.setOnAction(this::processButtonPress);
  root.getChildren().addAll(write);
  main = new Scene(root,300,300);
  stage.setScene(main);
  stage.show();
}
   public void processButtonPress(ActionEvent event) throws IOException{
   if (event.getSource() == write){
        //On button press write to file
        fw.write("Testing file writing");
        //Close filewriter
        fw.close();
     }
  }
}

我试图在网上找到答案,但我被教导处理按钮按下的方式与大多数其他示例不同(说 (this::processButtonPress) 的部分)。我不确定使用 try/catch 语句是否对我有帮助,因为我对这些没有任何经验,请原谅。我得到的具体错误是 "error: incompatible thrown types IOException in method reference"。感谢您的帮助。

我试图使这个问题切合主题并且易于解决。如果有任何明显的问题,请告诉我。

您绝对需要使用 try/catch 语句来捕获异常。

如果您像我展示的那样更新方法,您将捕获异常。

然后您需要添加代码来处理异常,这样程序才能成功继续。

    public void processButtonPress(ActionEvent event) {
        if (event.getSource() == write) {
            try {
                // On button press write to file
                fw.write("Testing file writing");
                // Close filewriter
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();

                // Code to handle goes here...
            }
        }
    }

我建议使用 try-with-resources statement 自动关闭您的编写器。

您也可以像这样实现操作处理程序:

write.setOnAction(event -> {
    if (event.getSource() == write) {
        try {
            try (FileWriter fw = new FileWriter(records)) {
                //On button press write to file
                fw.write("Testing file writing");
            }
        } catch (IOException e) {
            // TODO process the exception properly
            e.printStackTrace();
        }
    }
});