簡體   English   中英

在文本文件中添加新的文本行

[英]Adding new lines of text in a text file

我的應用記錄了聲音。 錄制聲音后,系統會要求用戶輸入新的文件名。 現在我接下來要做的是在文本文件中添加所有文件名,以便稍后我可以將其作為數組讀取以制作列表視圖。

這是代碼:

//this is in onCreate
File recordedFiles = new File(externalStoragePath + File.separator + "/Android/data/com.whizzappseasyvoicenotepad/recorded files.txt");
if(!recordedFiles.exists())
    {
            try {
                recordedFiles.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
//this executes everytime text is entered and the button is clicked
try {
            String content = input.getText().toString();
            FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(">" + content + ".mp3");
            bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

現在的問題是每次我記錄一個新文件時,前一行都會被覆蓋。 因此,如果我記錄了兩個文件'text1'和'text2',在我記錄text1之后,txt文件將顯示text1,但是在我記錄text2之后,text2將覆蓋text1而不是插入新行。

我嘗試添加:

bw.NewLine()

之前

bw.write(">" + content + ".mp3");

但它不起作用。

如果我錄制三個聲音並將它們命名為sound1,sound2和sound3,我希望這是結果:

>sound1
>sound2
>sound3

使用帶有boolean append參數的FileWriter構造函數

FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile(), true);
//                                                              ^^^^

這將讓文件在末尾附加文本而不是覆蓋以前的內容。

您可以通過添加line.separator 屬性來完成

 bw.write(">" + content + ".mp3");
 bw.write(System.getProperty("line.separator").getBytes());

如果它應該覆蓋, FileWriter將采用布爾值。 因此,如果您想要附加到文件而不是覆蓋,請使用true

更換

FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile());

代替

FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile(), true);

暫無
暫無

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

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