簡體   English   中英

Java刪除我的文件並創建一個新文件

[英]Java deletes my file and creates a new one

我正在嘗試完成銀行帳戶作業。 我有一個文本文件“ BankAccounts.txt”,如果沒有該名稱的文件,則會創建該文件。 但是,如果文件存在,則不創建它。 但是Java希望刪除其中的所有代碼:(。您能幫助我確定為什么會這樣嗎?謝謝<3

碼:

static Scanner keyboard = new Scanner(System.in);
static File file;
static PrintWriter Vonnegut; //a great writer
static FileReader Max;
static BufferedReader Maxwell;

public static void main(String[] args) {
    initialize();
}

static void initialize(){
    try { // creating banking file
        file = new File("src/BankAccounts.txt");
        if(!file.isFile()) {file.createNewFile();} //if it doesn't exist, create it
        Vonnegut = new PrintWriter("src/BankAccounts.txt","UTF-8");
        Max = new FileReader("src/BankAccounts.txt");
        Maxwell = new BufferedReader(Max);
        //get list of usernames and passwords for later
        usernames = new String[countLines() / 5];
        passwords = new String[usernames.length];
        checkingAccounts = new String[usernames.length];
        savingsAccounts = new String[usernames.length];
    } catch (IOException e) {
        e.printStackTrace();
    }
}

而且此方法始終返回0 ...不管我的文件中是否包含數據。

static int countLines() throws IOException {
    BufferedReader Kerouac = new BufferedReader(Max);

    int lines = 0;

    while(Kerouac.readLine() != null)
        lines++;

    Kerouac.close();
    System.out.println(lines);
    return lines;
}

運行程序后,除非調用調用寫入文件的方法,否則文件的所有內容都將消失。

if(!file.isFile()) {file.createNewFile();} //if it doesn't exist, create it

多余的。 去掉。

    Vonnegut = new PrintWriter("src/BankAccounts.txt","UTF-8");

這總是創建一個新文件,這就是為什么前一行多余的原因。 如果要在文件已經存在時追加到文件:

    Vonnegut = new PrintWriter(new FileOutputStream("src/BankAccounts.txt", true),"UTF-8");

true參數告訴FileOutputStream追加到文件。

請參閱Javadoc。

或使用FileWriter代替FileOutputStream,相同的原理。

創建PrintWriter ,它將始終從javadoc中刪除該文件(如果已存在):

...如果文件存在,則將其截斷為零大小...

(即其內容將被刪除)

代替使用FileReaderPrintWriter您需要使用RandomAccessFile來以這種方式寫入和/或讀取文件:

RandomAccessFile myFile = new RandomAccessFile("/path/to/my/file", "rw");

這樣,如果不存在則自動創建文件,如果存在則自動打開文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM