首页 > 解决方案 > 使用打印机写入文件

问题描述

嗨,我是文件 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 时,它都会覆盖最近的一对(用户名和密码)。有没有解决的办法?

标签: javaioprintwriter

解决方案


请改用此构造函数。 new FileOutputStream(info,true);


推荐阅读