如何在Java中打印到新的一行?

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”进行注册,那么它可以正常工作,但是如果我再次打开程序并使用不同的用户名和密码注册另一个用户,它将替换第一个用户名和密码。我需要在每次有人注册后自动换行。

如果您能提供一个最小化的例子,我们可以为您提供帮助。请参考如何创建一个最小、完整和可验证的例子(How to create a Minimal, Complete, and Verifiable example):http://stackoverflow.com/help/mcve。 - DavidPostill
1
你要找的术语是“如何将行附加到现有文件”。 - Pointy
1
@DavidPostill 我想主要问题是 PrintWriter 总是会重新创建文件。 - Luiggi Mendoza
2个回答

5

首先使用FileWriter包装您的文件:

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

以下是构造函数 FileWriter(String, boolean) 的描述:

构造一个 FileWriter 对象,给定一个文件名和一个布尔值,指示是否追加所写入的数据。

参数

fileName - String 系统相关的文件名。
append - boolean 如果为 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));

谢谢你们两位的帮助,现在完美运行 :) - greg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接