问题描述
我正在使用 Java Swing 库开发一个简单的 GUI 计算器,但遇到了我找不到解决方案的问题。我只是在学习Java,所以如果问题很简单,请不要严格评判我。
我的问题的主要思想是我试图使用 Java.io“文件处理”将数字保存到文件中,并在您重新打开计算器进入文本字段时获取该数字。
代码如下:
public void actionPerformed (ActionEvent e)
{
//---------------------------------------------------------------
if (e.getSource() == button_save) {
save = mytext.getText();
writeF(save); // problem is here "Unhandled exception type IOException"
}
else if (e.getSource() == button_recall) {
recall = readF(); // also here
mytext.setText(recall);
}
public static void writeF(String memory)throws IOException{
FileWriter writehandle = new FileWriter("C:\\Users\\Public\\Documents\\memory.txt");
BufferedWriter bw = new BufferedWriter(writehandle);
bw.write(memory);
bw.close();
writehandle.close();
}
public static String readF()throws IOException{
FileReader readhandle = new FileReader("C:\\Users\\Public\\Documents\\memory.txt");
BufferedReader br = new BufferedReader(readhandle);
String num = br.readLine();
br.close();
readhandle.close();
return num;
}
解决方法
解决方案:
else if (e.getSource() == button_save) {
save = mytext.getText();
try
{
writeF(save);
}
catch (IOException e1)
{
e1.printStackTrace();
} // problem is here "Unhandled exception type IOException"
}
else if (e.getSource() == button_recall) {
try
{
recall = readF();
}
catch (IOException e1)
{
e1.printStackTrace();
} // also here
mytext.setText(recall);
}