【问题标题】:Writing to a file with printwriter使用打印机写入文件
【发布时间】:2018-05-01 03:46:16
【问题描述】:

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

【问题讨论】:

    标签: java io printwriter


    【解决方案1】:

    Java FileWriter 构造函数是这样调用的:

    new 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();
            }
        }
    

    【讨论】:

      【解决方案2】:

      改用这个构造函数。 new FileOutputStream(info,true);

      【讨论】:

      • 它现在不写任何东西):无论如何感谢您的帮助
      猜你喜欢
      • 1970-01-01
      • 2016-09-28
      • 2012-03-31
      • 2017-08-18
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      相关资源
      最近更新 更多