公共类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
}
}
每当我添加新的用户名和密码时,它都会替换现有的用户名和密码。我希望它在新行上添加新的用户名和密码。
答案 0 :(得分:0)
在函数writeToUsersFile
中,替换以下行:
PrintWriter output = new PrintWriter(file);
带
PrintWriter output new PrintWriter(new FileWriter("users.txt", true));
还有一点,与你的问题无关:
除非这是一个玩具应用程序,否则我建议不要以明文形式将用户名和密码写入磁盘上的文件。您不希望密码位于磁盘上。您可能需要考虑在Java中使用一些密码存储(如OS X上的Keychain)或Java Key Store。
答案 1 :(得分:0)
正在覆盖该文件,使用true替代文件。请改为:
PrintWriter output = new PrintWriter(new FileWriter(file, true));