Pages

Wednesday, March 11, 2009

How to write new line to a file in JAVA

Printing a new line is …

       System.out.print(“\n”); You may feel a joke here.

 But when you are trying to do the same thing with a file it becomes a little tricky.

 Print(“\n”) will not print a new line to a file..

    The trick is also simple. You just have to add a carriage return before your new line. Remember before the new line..

 That means ::: Print(“\r\n”) ;

 So very simple here is a sample code with BufferedWriter.

 BufferedWriter bw = null;

        try {

            bw = new BufferedWriter(new FileWriter(new File("hello.txt")));

            bw.write("helo world" + "\r\n");

            bw.write("hello world 2");

            bw.flush();

            bw.close();

        } catch (IOException ex) {

            ex.printStackTrace();

        }

 

 

 

No comments:

Post a Comment