2013-12-10 32 views
1

您好我正在使用NetBeans更易於使用的圖形用戶界面。如何在使用java中的filewriter保存文件時設置目錄?

我試圖保存一個txt文件,這是我從用戶那裏得到的名稱,並使用FileWriter的,(不使用序列化)

我想我可以設置使用序列化的文件的保存位置(我不確定)

但是,我的代碼有點看起來很髒,如果我使用Serializable並且會導致一些錯誤。 (我使用2類)

無論如何,有沒有一種方法來設置保存與FileWriter的txt文件的目錄?

這是我的代碼,用於保存文件。

public boolean save() { 
    try { 
     File dir = new File("C:\\Users\\JSK\\Desktop\\BOARD\\data"); 

     String str = Title_field.getText() + ".txt"; 
     CheckFile(str); 
     CheckCbox(); 
     area.append("\n Written at :" + date_format.format(now.getTime())); 
     FileWriter fw = new FileWriter(str); 
     fw.write(area.getText()); 
     fw.close(); 
     JOptionPane.showMessageDialog(this, "Successfully Written"); 
     this.setVisible(false); 
     Title_field.setEditable(false); 
     area.setEditable(false); 
    } catch (FileNotFoundException ex) { 
     JOptionPane.showMessageDialog(this, "You Must Create A File First!", "File Missing", JOptionPane.ERROR_MESSAGE); 
    } catch (IOException ex) { 
     JOptionPane.showMessageDialog(this, "I/O ERROR", "Failed to save the file", JOptionPane.ERROR_MESSAGE); 
    } catch (FileExistException ex) { 
     JOptionPane.showMessageDialog(this, "File Already Exists, Please Change the title", "ERROR", JOptionPane.ERROR_MESSAGE); 
     area.setText(""); 
     return false; 
    } catch (CheckboxSelectionException ex) { 
     JOptionPane.showMessageDialog(this, "You must select at least one location", "ERROR", JOptionPane.ERROR_MESSAGE); 
     Title_field.setText(""); 
     area.setText(""); 
     return false; 
    } 

    return true; 
}  

目錄意味着,我要保存它的目錄,但它實際上節省了內部C:\用戶\ JSK \桌面\ BOARD

+0

創建一個OutputStream有效實例http://docs.oracle.com/javase /6/docs/api/java/io/OutputStream.html – AurA

回答

2

而是這行:

FileWriter fw = new FileWriter(str); 

試試這個:

FileWriter fw = new FileWriter(new File(dir, str)); 
相關問題