Search code examples
javaunixhexcarriage-returnlinefeed

Java - convert unix linefeed to carriage return


I build a string on a unix server and write it then down on a windows maschine. To make a linefeed I use "\r\n" but then the server only adds the unix linefeed "\n". The point is the eol is in hex 0a and I need 0d0a for other programs.

Has anyone an idea to convert the linefeeds before writing it down on the windows maschine?

To convert the string to hex then replace all 0a with 0d0a an convert it back to a string is not the best practise. Has anyone a better solution?


Solution

  • Writing "\r\n" to a file will output "\r\n", not "\n", to the file, even on *nix. Here's an example, using a BufferedWriter since at one point you said you were using one:

    import java.io.*;
    
    public class Example {
        public static final void main(String[] args) {
            System.out.println("Writing to test.txt");
            try (
                Writer w = new FileWriter("test.txt");
                BufferedWriter bw = new BufferedWriter(w);
            ) {
                bw.append("Testing 1 2 3");
                bw.append("\r\n");
                bw.append("More Testing");
                bw.append("\r\n");
            }
            catch (IOException ioe) {
                System.err.println("Error writing to file: " + ioe.getMessage());
            }
            System.out.println("Done");
        }
    }
    

    Running it:

    $ java Example
    Writing to test.txt
    Done
    

    Proof it writes \r\n (not just \n) to the output (yes, I'm using *nix, specifically Linux Mint 17.3):

    $ hexdump -C test.txt
    00000000  54 65 73 74 69 6e 67 20  31 20 32 20 33 0d 0a 4d  |Testing 1 2 3..M|
    00000010  6f 72 65 20 54 65 73 74  69 6e 67 0d 0a           |ore Testing..|
    0000001d