如何在Java中创建txt文件?

时间:2014-11-26 13:24:29

标签: 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

3 个答案:

答案 0 :(得分:2)

您可以使用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();

答案 1 :(得分:0)

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/

答案 2 :(得分:0)

好的,所以一旦你收到了用户的输入,这就是用来将用户名和密码写入文本文件的方法

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

EDIT ***

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

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

}