2015-10-26 51 views
0

公共类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 


} 

}

每次我添加一个新的用户名和passoword它取代现有的用户名和密码。我希望它在新行上添加新的用户名和密码。

+0

我不明白什么是具体的问题 – lrleon

+2

可能的复制[如何将文本追加到现有文件中Java](http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) –

回答

0

在功能writeToUsersFile,替换下面的行:

PrintWriter output = new PrintWriter(file); 

PrintWriter output new PrintWriter(new FileWriter("users.txt", true)); 

还多了一个点,这无关你的问题:

除非这是一个玩具应用程序,我会建议不要以纯文本形式将用户名和密码写入磁盘上的文件。你不希望密码像你的磁盘上一样。您可能需要考虑在Java中使用一些密码存储区(如OS X上的Keychain)或Java Key Store。

+0

谢谢。你能解释什么是布尔值?哦,这只是一个玩具应用程序。但是,什么是钥匙串,我怎样才能使用这个应用程序而不是.txt –

+1

为那个第二个参数传递'true'告诉它打开要附加的文件,而不是创建一个新文件。密钥存储或密钥链是秘密的安全存储。它通常用于存储私钥。我想他们也可以存储任意密码。但我现在不确定。相反,您可以选择加密密码以确保恶意程序无法以明文形式读取密码。有关更多详细信息,请参阅http://blog.jerryorr.com/2012/05/secure-password-storage-lots-of-donts.html。 – Venkat

0

的文件被覆盖,使用真正附加到文件instead.Try这个代替: PrintWriter output = new PrintWriter(new FileWriter(file, true));

相关问题