写入文件时新行

时间:2015-10-07 18:35:10

标签: java filewriter

我按了this链接,我想出了下面的代码

     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

图像

enter image description here

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

要添加线分隔符,您可以使用此功能。

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

希望有所帮助!