2017-07-07 60 views
0

我试图通过按下JavaFx中的按钮将数据写入文本文件。但是唯一的问题是,当我尝试使用声明,“在我的按钮处理方法中抛出IOException”时,事情似乎不起作用。这是我的代码。如何捕捉javafx中的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(); 
    } 
    } 
} 

我试图在网上找到答案,但我被教导要处理按下按钮的方式,从大多数人的例子(也称部分(这:: processButtonPress))不同。我不确定是否使用try/catch语句可以帮助我,因为我没有任何经验,请原谅我。我特别要得到的错误是“错误:方法参考中出现不兼容的抛出类型IOException”。感谢您的帮助。

我试着在主题上提出这个问题,并且很容易解决。请让我知道是否有任何明显的问题。

+0

你必须处理方法中IOException异常。 – f1sh

回答

1

您绝对需要使用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... 
      } 
     } 
    } 
+0

非常出色!我将不得不更多地研究这些陈述。谢谢你的帮助! –

+0

是的,很难写出没有异常处理的好代码。只要你想知道,try块中的代码将一行一行地运行,直到它抛出异常为止。一旦抛出,try块中的所有附加代码都将被跳过。只有catch块中的代码才会执行​​。 – gabe870

+0

如果你解释了为什么IOException不能在动作处理器的throws子句中,这将是一个更好的答案。 – VGR

2

我建议使用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(); 
     } 
    } 
});