您好我是一名提交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时,它都会覆盖最近的一对(用户名和密码)。有办法解决这个问题吗?
答案 0 :(得分:0)
请改用此构造函数。 new FileOutputStream(info,true);
答案 1 :(得分:0)
Java FileWriter构造函数的调用如下:
new FileWriter(String s,boolean append);
这个简单的构造函数表示你想以追加模式写入文件。
请尝试以下代码:
dir