[英]Writing to a file with printwriter
嗨,我是文件I / O的初學者,我在寫入文件時遇到了一個小問題。 我的程序應該做的是將用戶名和密碼寫入文件。 這是我的代碼(由於代碼特定於程序,因此無法在代碼后描述我的問題):
public class Helper {
public static void main(String[] args) throws Exception {
Home();
UserInput();
}
private static void Home() throws FileNotFoundException{
System.out.println("Here are the instrucions for the chat program:");
System.out.println("Type *R for registration" );
}
private static void UserInput() throws Exception{
Scanner scan = new Scanner(System.in);
String input = scan.next();
if(input.equals("*R")){
Register();
}
main(new String[0]);
}
private static void Register() throws FileNotFoundException{
try{
File info = new File("info.txt");
info.createNewFile();
FileOutputStream outputStream = new FileOutputStream(info);
PrintWriter out = new PrintWriter(outputStream);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a username: ");
String username = scan.nextLine();
System.out.println("Enter a password: ");
String password = scan.nextLine();
out.println(username + " " + password);
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
我需要的是info.txt文件,用於將每對用戶名和密碼存儲在不同的行中,但是它僅存儲最新的用戶名和密碼。 也就是說,每次我寫入info.txt時,它都會覆蓋最新的密碼對(用戶名和密碼)。 有沒有解決的辦法?
請改用此構造函數。 new FileOutputStream(info,true);
Java FileWriter構造函數的調用方式如下:
新的FileWriter(String s,boolean append);
這個簡單的構造函數指示您要在追加模式下寫入文件。
嘗試以下代碼:
private static void Register() throws FileNotFoundException{
try{
FileWriter fw = new FileWriter("info.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a username: ");
String username = scan.nextLine();
System.out.println("Enter a password: ");
String password = scan.nextLine();
out.println(username + " " + password);
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.