如何更正netbeans中“保存到文件”按钮的错误?

时间:2015-03-26 07:01:33

标签: java netbeans jtable

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;


private void btnFileSaveActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:

    BufferedWriter bfw = new BufferedWriter(new FileWriter("D:\\CedulaList.txt"));

                  for (int i = 0 ; i < tableCedula.getRowCount(); i++)
                  {

                    for(int j = 0 ; j < tableCedula.getColumnCount();j++)
                    {
                        bfw.newLine();
                        bfw.write((String)(tableCedula.getValueAt(i,j)));
                        bfw.write("\t");;
                    }
                  }
                  bfw.close();



}   

我似乎没有掌握如何解决这个问题。错误说,&#34;未报告的异常IOException;必须被抓或宣布被抛出。

转换为try-with-resources。&#34;

2 个答案:

答案 0 :(得分:0)

throws子句添加到方法签名

private void btnFileSaveActionPerformed(java.awt.event.ActionEvent evt) throws IOException {    

或使用try catch

private void btnFileSaveActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
   try {
    BufferedWriter bfw = new BufferedWriter(new FileWriter("D:\\CedulaList.txt"));

                  for (int i = 0 ; i < tableCedula.getRowCount(); i++)
                  {

                    for(int j = 0 ; j < tableCedula.getColumnCount();j++)
                    {
                        bfw.newLine();
                        bfw.write((String)(tableCedula.getValueAt(i,j)));
                        bfw.write("\t");;
                    }
                  }
                  bfw.close();
    } catch(IOException e){
         //Handle the exception
    }


}   

答案 1 :(得分:0)

你需要抛出/ try-catch为:

private void btnFileSaveActionPerformed(java.awt.event.ActionEvent evt) 
{                                            
   try{
      BufferedWriter bfw = new BufferedWriter(new FileWriter("D:\\CedulaList.txt"));

              for (int i = 0 ; i < tableCedula.getRowCount(); i++)
              {

                for(int j = 0 ; j < tableCedula.getColumnCount();j++)
                {
                    bfw.newLine();
                    bfw.write((String)(tableCedula.getValueAt(i,j)));
                    bfw.write("\t");;
                }
              }
   }catch(Exception ex){

   }finally{
      if(bfw != null){
         bfw.close();
      }
   }    
}