[英]How to write line by line in an output file without replacing the old line
[英]How to write to a file on new line without replacing the existing text in file?
公共類CreateNewUser {
public String fullName;
public int age;
public String school;
public String username;
public String password;
File file = new File("users.txt");
public void setFullName(String n) {
this.fullName = n;
}
public void setAge(int a) {
this.age = a;
}
public void setUsername(String u) {
this.username = u;
}
public void setPassword(String p) {
this.password = p;
}
public String getFullName() {
return fullName;
}
public String getSchool() {
return school;
}
public int getAge() {
return age;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
//write all info on to .txt
public void writeToInfoFile(String u, String p, String s, int a) {
}
//write username & password to a sepereate file (users.txt)
public void writeToUsersFile(String u, String p) {
try{
PrintWriter output = new PrintWriter(file);
//if username exists throw exception
output.println(username + " " + password);
output.close();
} catch (IOException ex){
System.out.println("ERROR: file not found.");
}
}
}
公共類CreateNewUserTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
CreateNewUser raul = new CreateNewUser();
CreateNewUser jake = new CreateNewUser();
String username, password;
String uni;
int age;
//Raul
System.out.printf("\tHello! Welcome to Ponder\t");
System.out.println();
System.out.print("Enter desired username: ");
username = in.nextLine();
raul.setUsername(username);
System.out.println();
System.out.print("Enter desired password: ");
password = in.nextLine();
raul.setPassword(password);
raul.writeToUsersFile(username, password);
in.close(); //close scanner
}
}
每當我添加新的用戶名和密碼時,它都會替換現有的用戶名和密碼。 我希望它在新行上添加新的用戶名和密碼。
在函數writeToUsersFile
,替換以下行:
PrintWriter output = new PrintWriter(file);
與
PrintWriter output new PrintWriter(new FileWriter("users.txt", true));
還有一點,與您的問題無關:
除非這是一個玩具應用程序,否則建議不要將純文本的用戶名和密碼寫入磁盤上的文件。 您不希望密碼像磁盤上那樣亂七八糟。 您可能要考慮使用Java中的一些密碼存儲(例如OS X上的Keychain)或Java密鑰存儲。
正在覆蓋文件,而是使用true追加到文件。嘗試以下操作: PrintWriter output = new PrintWriter(new FileWriter(file, true));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.