簡體   English   中英

寫入文本文件而不覆蓋先前的條目

[英]Write to text file without overwriting previous entry

我正在使用它來寫入文本文件。 程序打開時工作正常,但是當我關閉並重新打開並再次開始保存時,它會完全覆蓋以前的數字。

private void writeNumbers(ArrayList<String> nums)
{
    try 
    {
        PrintStream oFile = new PrintStream("lottoNumbers.txt");
        oFile.print(nums);
        oFile.close();
    }
    catch(IOException ioe)
    {
        System.out.println("I/O Error" + ioe);
    }
}

您是否在啟動程序時閱讀此文本文件? 如果您正在寫入的文件已經存在,它總是會覆蓋它。 如果要將其添加到文件中,則需要在啟動程序時將其讀入,將該數據保存在某處,然后將舊數據+新數據寫入文件。

盡管可能有一種更簡單的方法,但我過去就是這樣做的。

編寫一個 if 語句來檢查文件是否存在,如果存在,您可以使用“file.append”,否則創建一個新文件。

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/mkyong/filename.txt");

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

你可以試試這個追加模式

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

或者

FileUtils.writeStringToFile(file, "String to append", true);

暫無
暫無

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

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