[java] Carriage Return\Line feed in Java

I have created a text file in Unix environment using Java code.

For writing the text file I am using java.io.FileWriter and BufferedWriter. And for newline after each row I am using bw.newLine() method (where bw is object of BufferedWriter).

And I'm sending that text file by attaching in mail from Unix environment itself (automated that using Unix commands).

My issue is, after I download the text file from mail in a Windows system, if I opened that text file the data is not properly aligned. newline() character is not working, I think so.

I want same text file alignment as it is in Unix environment, if I opened the text file in Windows environment also.

How do I resolve the problem?

Java code below for your reference (running in Unix environment):

File f = new File(strFileGenLoc);
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
rs = stmt.executeQuery("select * from jpdata");
while ( rs.next() ) {
    bw.write(rs.getString(1)==null? "":rs.getString(1));
    bw.newLine();
}

This question is related to java carriage-return line-endings eol linefeed

The answer is


The method newLine() ensures a platform-compatible new line is added (0Dh 0Ah for DOS, 0Dh for older Macs, 0Ah for Unix/Linux). Java has no way of knowing on which platform you are going to send the text. This conversion should be taken care of by the mail sending entities.


Don't know who looks at your file, but if you open it in wordpad instead of notepad, the linebreaks will show correct. In case you're using a special file extension, associate it with wordpad and you're done with it. Or use any other more advanced text editor.


If I understand you right, we talk about a text file attachment. Thats unfortunate because if it was the email's message body, you could always use "\r\n", referring to http://www.faqs.org/rfcs/rfc822.html

But as it's an attachment, you must live with system differences. If I were in your shoes, I would choose one of those options:

a) only support windows clients by using "\r\n" as line end.

b) provide two attachment files, one with linux format and one with windows format.

c) I don't know if the attachment is to be read by people or machines, but if it is people I would consider attaching an HTML file instead of plain text. more portable and much prettier, too :)


Encapsulate your writer to provide char replacement, like this:

public class WindowsFileWriter extends Writer {

    private Writer writer;

    public WindowsFileWriter(File file) throws IOException {
        try {
            writer = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-15");
        } catch (UnsupportedEncodingException e) {
            writer = new FileWriter(logfile);
        }
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        writer.write(new String(cbuf, off, len).replace("\n", "\r\n"));
    }

    @Override
    public void flush() throws IOException {
        writer.flush();
    }

    @Override
    public void close() throws IOException {
        writer.close();
    }

}

bw.newLine(); cannot ensure compatibility with all systems.

If you are sure it is going to be opened in windows, you can format it to windows newline.

If you are already using native unix commands, try unix2dos and convert teh already generated file to windows format and then send the mail.

If you are not using unix commands and prefer to do it in java, use ``bw.write("\r\n")` and if it does not complicate your program, have a method that finds out the operating system and writes the appropriate newline.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to carriage-return

Create Carriage Return in PHP String? What is the difference between a "line feed" and a "carriage return"? How can I insert new line/carriage returns into an element.textContent? What are the differences between char literals '\n' and '\r' in Java? What's the Use of '\r' escape sequence? Carriage return and Line feed... Are both required in C#? Find and replace - Add carriage return OR Newline In C#, what's the difference between \n and \r\n? See line breaks and carriage returns in editor What are carriage return, linefeed, and form feed?

Examples related to line-endings

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style Git status ignore line endings / identical files / windows & linux environment / dropbox / mled Fixing Sublime Text 2 line endings? How to read lines of a file in Ruby 'Incomplete final line' warning when trying to read a .csv file into R How to find out line-endings in a text file? Carriage Return\Line feed in Java Why should I use core.autocrlf=true in Git? What is the difference between \r and \n? What does Visual Studio mean by normalize inconsistent line endings?

Examples related to eol

Replace CRLF using powershell Windows command to convert Unix line endings? EOL conversion in notepad ++ Force LF eol in git repo and working copy Choose newline character in Notepad++ How do I use System.getProperty("line.separator").toString()? Carriage Return\Line feed in Java How do I get a platform-dependent new line character? What's the best CRLF (carriage return, line feed) handling strategy with Git? When do I use the PHP constant "PHP_EOL"?

Examples related to linefeed

What is the difference between a "line feed" and a "carriage return"? Carriage return and Line feed... Are both required in C#? In C#, what's the difference between \n and \r\n? What are carriage return, linefeed, and form feed? Writing a new line to file in PHP (line feed) Carriage Return\Line feed in Java