繁体   English   中英

如何在Java中创建txt文件?

[英]How to create a txt file in 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.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对象创建新的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();
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
    public static void main(String[] args) {
        try {

            String content = "This is the content to write into file";

            // File file = new File("/users/your_user_name/filename.txt");// unix case
            File file = new File("c:\\filename.txt"); //windows case

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

资料来源: http : //www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/

好的,一旦收到用户的输入,便可以将用户名和密码写入文本文件

         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 ^^

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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