Force End-of-line delimiter as LF only Tag(s): IO


When running under the Windows, Java will use the CR-LF combination as the end-of-linedelimiter. To force the LF character as the end-of-line, you can set a System property line.separator. Note that this will affect the whole JVM.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class LfOnlyDemo {
   public static void main(String[] args) throws IOException {
      LfOnlyDemo.demo();
   }

   public static void demo() throws IOException{
      System.setProperty("line.separator", "\n");

      FileOutputStream fos = new FileOutputStream("c:/temp/foo/lf.txt");
      PrintWriter out = new PrintWriter(fos);

      try {
         out.println("**********");
         out.println("* Real's *");
         out.println("* HowTo  *");
         out.println("**********");
      }
      finally {
         out.flush();
         out.close();
      }
   }
}

Another way is to override the PrintWriter to force the use of LF-only as line delimiter.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class LfOnlyDemo {

   public static void main(String[] args) throws IOException {
      LfOnlyDemo.demo();
   }

   public static void demo() throws IOException{
      //
      //  the following will use LF as EOL character on all platforms
      //
      FileOutputStream fos = new FileOutputStream("c:/temp/foo/lf.txt");
      // force EOL Unix-style LF-only
      PrintWriter out1 = new PrintWriter(fos) {
         @Override
         public void println() {
            write('\n');
         }
      };
      try {
         out1.println("**********");
         out1.println("* Real's *");
         out1.println("* HowTo  *");
         out1.println("**********");
      }
      finally {
         out1.flush();
         out1.close();
      }

      //
      //  on Windows, the following will use CRLF as EOL character
      //  on Linux/Unix, the following will use LF as EOL character
      //
      FileOutputStream fos2 = new FileOutputStream("c:/temp/foo/crlf.txt");
      PrintWriter out2 = new PrintWriter(fos2);
      try {
         out2.println("**********");
         out2.println("* Real's *");
         out2.println("* HowTo  *");
         out2.println("**********");
      }
      finally {
         out2.flush();
         out2.close();
      }
   }
}


comment Comments