2013-10-30 36 views
1

我在創建輸出流文件時遇到了問題。如何使outputstream在文件不存在的情況下生成文件?

OutputStream output = new FileOutputStream(username + ".txt"); 
byte buffer[] = data.getBytes(); 
output.write(buffer); 
output.close(); 

它工作得很好,直到我做了另一種方法:

public void actionPerformed (ActionEvent e) //When a button is clicked 
{ 
    if (e.getSource() == encrBtn) 
    { 
     menu.setVisible(false); 
     createProfile(); 
     menu.setVisible(true); 
    } 
    else 
    { 
     if (e.getSource() == decrBtn) 
     { 
     menu.setVisible(false); 
     viewProfile(); 
     menu.setVisible(true); 
     } 
     else 
     { 
     if (e.getSource() == exitBtn) 
     { 
      JOptionPane.showMessageDialog(null, "Goodbye!"); 
     System.exit(0); 
     } 
     } 
    } 
} 

以前,我把每於

createprofile(); 

方法調用方法開始拋出異常(在哪個輸出流是)。但現在我得到

ProfileEncryption_2.java:54: error: actionPerformed(ActionEvent) in ProfileEncryption_2  cannot implement actionPerformed(ActionEvent) in ActionListener 
public void actionPerformed (ActionEvent e) throws Exception //When a button is clicked 
     ^
overridden method does not throw Exception 

以前,我在想,如果有另一種方式拋出異常:cannot implement actionPerformed(ActionEvent) in ActionListener 但現在我認爲,這將是更好的以某種方式強制的OutputStream使文件。我已經搜索了多個這樣的措辭,但我現在知道如何做到這一點...我發現的東西也沒有工作。

回答

1

ActionListener接口沒有聲明它的actionPerformed方法拋出任何類型的Exception,你不能改變這個簽名。

您需要捕捉並管理該方法中的異常。

public void actionPerformed(ActionEvent e) //When a button is clicked 
{ 
    if (e.getSource() == encrBtn) { 
     menu.setVisible(false); 
     try { 
      createProfile(); 
     } catch (Exception exp) { 
      exp.printStackTrace(); 
      JOptionPane.showMessageDialog(this, "Failed to create profile", "Error", JOptionPane.ERROR_MESSAGE); 
     } 
     menu.setVisible(true); 
    } else { 
     //... 
    } 
} 

FileOutputStream能夠創建文件,如果它不存在的,但是,如果路徑不或可能有問題,如果你沒有足夠的權限寫入到指定位置或任意數量的其他可能的問題...

+0

非常感謝!有用。 – Greatmar2

0

您遇到類型不匹配。 ActionListener接口的actionPerformed方法不包含包含throws Exception子句,因此不能在您覆蓋的方法中包含一個子句。一個簡單的解決辦法是捕獲拋出的任何Exception,並重新拋出它作爲RuntimeException。由於RuntimeException未被選中,因此您不需要將其包含在throws子句中。

public void actionPerformed (ActionEvent e) //When a button is clicked 
{ 
    try { // <-- Added try block 
    if (e.getSource() == encrBtn) 
    { 
      menu.setVisible(false); 
     createProfile(); 
     menu.setVisible(true); 
    } 
    else 
    { 
     if (e.getSource() == decrBtn) 
     { 
      menu.setVisible(false); 
      viewProfile(); 
      menu.setVisible(true); 
     } 
     else 
     { 
      if (e.getSource() == exitBtn) 
      { 
       JOptionPane.showMessageDialog(null, "Goodbye!"); 
      System.exit(0); 
      } 
     } 
    } 
    } 
    catch (Exception e) { // <-- Catch exception 
    throw new RuntimeException(e); // <-- Re-throw as RuntimeException 
    } 
} 

它通常是更好的,如果能夠真正處理異常,但如果你只是想看到的異常(例如,用於調試),那麼我會說,在RuntimeException包裝,並重新把它扔是除了在您的所有方法簽名的末尾添加throws Exception之外,還有一點點清潔。如果您可以將catch模塊中的Exception類型縮小到您期望的實際異常類型,那也會更好。

相關問題