簡體   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