[英]How do I print to a new line in java?
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”注册它可以正常工作,但如果我再次使用程序并使用不同的用户名和密码注册另一个用户,它将替换第一个用户名并通过。 每次有人报名时我都需要它去新线。
首先使用FileWriter
包装文件:
PrintWriter writer = new PrintWriter(new FileWriter("src/file", true));
这是FileWriter(String, boolean)
的构造函数的描述:
在给定文件名的情况下构造FileWriter对象,该文件名带有一个布尔值,指示是否附加写入的数据。
参数
fileName
- String依赖于系统的文件名。
append
- boolean如果为true
,则数据将写入文件的末尾而不是开头
您正在使用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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.