2014-09-06 53 views
4
boolean valid = false; 
String user = txtUser.getText(); 
String pass = txtPass.getText(); 
try { 
    PrintWriter writer = new PrintWriter("src/file"); 
    writer.println("The line"); 
    writer.println(user + "#" + pass); 
    JOptionPane.showMessageDialog(null,"Sign Up"complete",JOptionPane.INFORMATION_MESSAGE); 
    writer.close(); 
} catch(Exception e) { 
} 

我正在註冊一個頁面,我已經創建了登錄頁面。代碼中的#用於將用戶名和密碼分開。一切正常,但問題在於,我每次註冊時都會替換上次我提供的註冊信息。因此,如果我第一次使用用戶名「greg」和密碼「877」註冊,它可以正常工作,但如果我再次使用另一個用戶名和密碼註冊另一個用戶,則會替換第一個用戶名和密碼。每次有人註冊後,我都需要它去換新線。如何在java中打印新行?

+0

如果你創建了一個小例子,我們可以提供幫助。請參見[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – DavidPostill 2014-09-06 14:15:10

+1

您正在查找的術語是「如何將行附加到現有文件」。 – Pointy 2014-09-06 14:15:35

+1

@DavidPostill我想主要的問題是'PrintWriter'將一直重新創建文件。 – 2014-09-06 14:15:38

回答

5

FileWriter第一包裝你的文件:

PrintWriter writer = new PrintWriter(new FileWriter("src/file", true)); 

這裏是爲FileWriter(String, boolean)構造函數的說明:

構造給定表示文件名用布爾一個FileWriter對象是否要附加寫入的數據。

參數

fileName - 字符串與系統有關的文件名。
append - 布爾如果true,然後數據將被寫入到文件而不是開頭

0

您使用public PrintWriter(File file)寫入文件

javadoc說結束 -

parameter specifies the file to use as the destination of this writer. If the file 
exists then it will be truncated to zero size; otherwise, a new file will be created. 
The output will be written to the file and is buffered. 

所以在你的情況下,你需要附加文本到現有文件的內容,所以Luiggi說FileWriter是你的朋友

FileWriter, a character stream to write characters to file. By default, it will 
replace all the existing content with new content, however, when you specified a 
true (boolean) value as the second argument in FileWriter constructor, it will keep 
the existing content and append the new content in the end of the file. 

嘗試以這種方式

PrintWriter outputFile = new PrintWriter(new FileWriter("src/file", true)); 
+0

感謝您的幫助,現在完美工作:) – greg 2014-09-07 08:02:47