如何在Java中创建txt文件?

如何在Java中创建txt文件?,java,Java,我只是想要一个程序来注册一个用户,然后创建一个txt文件来存储信息。我知道它必须使用createNewFile方法,但我不知道如何使用它。我会在我的代码中尝试: import java.util.*; public class File{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); byte option=0; do{ System.out.pr

我只是想要一个程序来注册一个用户,然后创建一个txt文件来存储信息。我知道它必须使用createNewFile方法,但我不知道如何使用它。我会在我的代码中尝试:

import java.util.*;

public class File{


public static void main(String args[]){
    Scanner sc = new Scanner(System.in);

byte option=0;

    do{
        System.out.println("\nMENU:\n");
        System.out.println("0.-EXIT");
        System.out.println("1.-REGISTER USER");
        System.out.println("\nPLEASE ENTER YOUR CHOICE:");
        option = sc.nextByte();
    }while(option!=0);

}//main
}//File

可以使用文件对象创建新文件,例如:

File createFile = new File("C:\\Users\\youruser\\desktop\\mynewfile.txt");
createFile.createNewFile();
如果要读取和写入文件,可以使用PrintWriter或其他写入机制:

PrintWriter pw = new PrintWriter(createFile);

pw.write("File Contents");
//when you are done flush and close the pw
pw.flush();
pw.close();
如果需要附加到文件,可以执行以下操作:

PrintWriter pw = new PrintWriter(new FileOutputStream(createFile, true)); //true means append here

pw.append("File Contents");
//when you are done flush and close the pw
pw.flush();
pw.close();

来源:

好的,所以一旦用户输入了用户名和密码,您就可以使用它将用户名和密码写入文本文件

         try {
        File file = new File("userInfo.txt");
        BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
              //set to true so you can add multiple users(it will append (false will create a new one everytime)) 

            output.write(username + "," + password);

        output.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
编辑***

您可以将所有这些放在一个方法中,并在每次添加用户时调用它

public void addUser(String username, String password){
        //my code from above ^^

}

查看Java教程,其中有一章介绍该主题:
public void addUser(String username, String password){
        //my code from above ^^