繁体   English   中英

用printwriter写文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM