alex wilhelm
alex wilhelm

Reputation: 233

How to write a separate line for a text file

So when I write to my text file using FileOutputSstream I have used both

fos.write(("0"+"\n").getBytes());

and

fos.write(System.getProperty("line.separator").getBytes());

and neither of them work... they still print on the same line...

Any thoughts?

Upvotes: 3

Views: 6680

Answers (6)

gifpif
gifpif

Reputation: 4917

You can use println method

PrintStream ps=new PrintStream(new FileOutputStream("outputPath"));
for(String line:lines)
    ps.println(line);

Upvotes: 1

alex wilhelm
alex wilhelm

Reputation: 233

Ok so I figured it out... for some reason when I tried every example here the only thing that worked was ps.print("one\r\n"); Its really strange since I have know idea why it works but it does...

Upvotes: 2

tucuxi
tucuxi

Reputation: 17945

Newlines are different in each platform. For unix systems (MacOS X, Linux, ... and Android, since it uses a modified linux kernel), the line-separator is 0x0A; for MS Windows, it its two bytes long: 0x0D,0x0A; for old-school MacOS, it is 0x0D.

This means that an Android-newline written by Android will be invisible when opened by a particularly stupid Windows program such as Notepad.exe. A wiser program (such as a programming editor or an IDE) will display it without trouble.

Upvotes: 1

Alex Orzechowski
Alex Orzechowski

Reputation: 377

Use this:

public  byte[] newLine() {
    byte[] temp = new byte[2];
    temp[0] = 13;
    temp[1] = 10;
    return temp;
}

Just write this to your FileOuputStream. Like this:

    FileOutputStream.write(newLine());

This will simply write the bytes: 13 and 10.

Upvotes: 0

apesa
apesa

Reputation: 12443

You have to append the line seperator / break like this.

Try

String separator = System.getProperty("line.separator");
    fos.append(seperator);

Upvotes: -1

Mert
Mert

Reputation: 6572

use a PrintStream

System.out is a PrintStream for example.

You say you have a FileOutputStream. Then,

FileOutputStream f = new FileOutputStream("test.txt");
PrintStream ps = new PrintStream(f);
ps.print("line1");
ps.println(); //this writes your new line
ps.print("line2");
ps.close();

also you can use;

BufferedWriter fos = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
      fos.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      fos.newLine();

Upvotes: 1

Related Questions