DataOutputStream New Line Java

General new line character is discussed in Java New Line.

Infact, new line character is operating system dependent. To know the new line character supported by the OS, use line.separator of getProperty() defined in System class as follows.

String newLine = System.getProperty(“line.separator”);

The above newLine string object can be used in programming to give new line. DataOuputStream does not have any builtin method to give new line. But BufferedWriter has a builtin method newLine() which internally uses the above statement.

Following example uses DataOutputStream New Line.
import java.io.*;
public class UsingNewLine
{
  public static void main(String args[]) throws IOException
  {
    DataOutputStream dos = new DataOutputStream(new FileOutputStream("def.txt"));

    dos.writeBytes("Hello");
    dos.writeBytes("World");

    String newLine = System.getProperty("line.separator");

    dos.writeBytes(newLine);
    dos.writeBytes("Greetings");
    dos.writeBytes(newLine);
    dos.writeBytes("From way2java Readers");
    dos.close();
  }
}

DataOutputStream New Line JavaOutput Screenshot on DataOutputStream New Line Java in File def.txt

dos.writeBytes(newLine);
dos.writeBytes(“Greetings”);
dos.writeBytes(newLine);
dos.writeBytes(“From way2java Readers”);

First two lines come in one line. But later two output comes in two different lines due to the use of newLine returned by System.getProperty(“line.separator”).

The newLine can be used with System.out.println() also as follows.

System.out.print(“Hello”);
System.out.print(newLine);
System.out.print(“World”);

You get Hello and World in two lines. See the Screenshot.
DataOutputStream New Line

Leave a Comment

Your email address will not be published.