簡體   English   中英

寫入文件時換行

[英]New Line while writing into file

我點擊了鏈接,然后想到了以下代碼

     try {
        File file = new File(
                "C:/dataset.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
        BufferedWriter bw = new BufferedWriter(fw);

        List<Integer> data = generateData(args);

        // one per line
        for (final int i : data) {
            bw.write(i);
            bw.newLine(); // Here it throws NullPointerException
        }
        bw.close();
    } catch (IOException e) {
        System.out.print(e);
    }

注意:即使我移動bw.newLine(); for循環之前,它拋出NullPointerException

圖片

在此處輸入圖片說明

我有什么想念的嗎?

要添加行分隔符,您可以使用它。

    //to add a new line after each value added to File
    String newLine = System.getProperty("line.separator"); 

然后這樣稱呼它:

    bw.write(newLine);

編輯:由於您不能將System.getProperty與BufferWriter一起使用,因此建議以下代碼:

private FileOutputStream fOut;
private OutputStreamWriter writer;
fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(fOut);
writer.append(.... whatever you wish to append ...);
writer.append(separator);
writer.flush();
fOut.close();

希望有幫助!

暫無
暫無

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

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