Junaid S.
Junaid S.

Reputation: 2642

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

enter image description here

Am I missing anything ?

Upvotes: 0

Views: 563

Answers (1)

Shrey
Shrey

Reputation: 671

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!

Upvotes: 1

Related Questions