简体   繁体   中英

New Line while writing into file

I followed this link and I came up with below code

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

NOTE: Even if I move bw.newLine(); before for loop, it throws NullPointerException .

Image

在此处输入图片说明

Am I missing anything ?

To add a line seperator you could use this.

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

and then call it like so:

    bw.write(newLine);

EDIT: since you cant use a System.getProperty with a BufferWriter I would suggest the code below:

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

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM