这是我的代码到目前为止,但它已经覆盖了我在文本文件中的内容。我想要的是将它添加到文本文件中的新行。
import java.io.*;
import java.util.Scanner;
public class Login{
public static void main(String[] args) throws IOException {
Scanner s1,s2;
s1 = new Scanner(new FileInputStream("login.txt"));
s2 = new Scanner(System.in);
boolean loggedIn = false;
String name,pword,n,p;
System.out.println("Are you a new user? (Type y for yes or n for no)");
String nU = s2.next();
if (nU.equals("n"))
{
System.out.println("Enter username:");
n=s2.next();
System.out.println("Enter password:");
p=s2.next();
while(s1.hasNext()){
name=s1.next();
pword=s1.next();
if(n.equals(name) && p.equals(pword)){
System.out.println("You are logged in.");
loggedIn = true;
break;
}
}
if(!loggedIn)
System.out.println("Incorrect password or username.");
}
else if (nU.equals("y"))
{
这里是我的代码问题所在,因为这是将它写入文件的地方。
PrintWriter out = new PrintWriter("login.txt");
System.out.println("Enter username:");
n=s2.next();
System.out.println("Enter password:");
p=s2.next();
out.append(n);
out.append(p);
out.close();
System.out.println("Account has been created and you are logged in.");
}
else
System.out.println("Invalid response.");
答案 0 :(得分:11)
建议使用BufferedWriter
和FileWriter
的链,当使用其构造函数之一时,关键点是FileWriter
会将String附加到当前文件中,以便通过添加来实现appaneding true
最后一个参数
new FileWriter("login.txt", true)
当我们用BufferedWriter
对象包围它时为了更高效,如果要写入文件的时间,那么它将字符串缓存在大块中并将大块写入文件显然你可以节省大量的时间来写入文件
注意:有可能不使用BuffredWriter
,但建议使用它,因为它具有更好的性能和缓冲大块字符串并将其写入一次的能力
只需更改
即可PrintWriter out = new PrintWriter("login.txt");
到
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));
示例:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));) {
String data = "This content will append to the end of the file";
File file = new File("login.txt");
out.println(data);
} catch(IOException e) {
}
可以在不使用BufferedWriter
的情况下解决此问题,但是我提到的性能会很低。
示例:
try (PrintWriter out = new PrintWriter(new FileWriter("login.txt", true));) {
String data = "This content will append to the end of the file";
File file = new File("login.txt");
out.println(data);
} catch (IOException e) {
}
答案 1 :(得分:4)
FileWriter fw = new FileWriter(filename,true);
//the true will append the new data to the existing data
像这样的东西
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("login.txt", true)))
out.println(n);
out.println(p);
out.close();
答案 2 :(得分:0)
非常简单的例子就是这个。
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
File file = new File(workingDir+"/WebContent/Files/login.txt");
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
printWriter.println(workingDir);
printWriter.println("Good thing");
printWriter.close();
希望它有所帮助。