Carriage Return\Line feed in Java
Asked Answered
C

6

55

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();
}
Coyle answered 14/5, 2010 at 8:25 Comment(2)
You used a code block for the text?Fortney
Will the target system for opening the file always be windows, or will it vary?Odometer
O
62

Java only knows about the platform it is currently running on, so it can only give you a platform-dependent output on that platform (using bw.newLine()) . The fact that you open it on a windows system means that you either have to convert the file before using it (using something you have written, or using a program like unix2dos), or you have to output the file with windows format carriage returns in it originally in your Java program. So if you know the file will always be opened on a windows machine, you will have to output

bw.write(rs.getString(1)==null? "":rs.getString(1));
bw.write("\r\n");

It's worth noting that you aren't going to be able to output a file that will look correct on both platforms if it is just plain text you are using, you may want to consider using html if it is an email, or xml if it is data. Alternatively, you may need some kind of client that reads the data and then formats it for the platform that the viewer is using.

Odometer answered 14/5, 2010 at 8:44 Comment(7)
The end-of-line sequence on Windows is CR LF, not LF CR, so I would change that to br.write("\r\n"); (instead of \n\r).Synopsis
@Synopsis - thanks, I've updated it accordingly, I knew it was there or thereaboutsOdometer
If I run the same code in a Windows system, would I get the same text file? Or would the text file now have \r\r\n (the second \r resulting from Windows Java expanding \n to \r\n)?Tompion
Never mind that, I found out that \n is NOT converted to \r\n by Windows Java. Using \r and/or \n in your string actually enforces a particular line ending style independent of the platform Java is running on.Tompion
@Tompion nothing is ever automgaically converted - in this example you're writing raw byte values into a fileOdometer
Why don't you concatenate inline? Like this: bw.write(rs.getString(1)==null? "":rs.getString(1) + "\r\n");Thun
I've tried this solution and it is not working for me. I'm opening the text file in windows. Below is my code: try { while (rset.next()) osw.write(rset.getString(1)==null? "":rset.getString(1)); osw.write(System.lineSeparator()); //osw.write("\r\n"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Print col 1Aharon
F
7

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.

Forsooth answered 14/5, 2010 at 8:30 Comment(3)
i am not getting you. could you please explain it.Coyle
Suppose you edit a text with your favorite editor in Linux. What will it do when you press enter ? It will append a new-line character. Before doing so, he will ask himself: what is my newline character ? Being Linux he will answer: 0Ah of course. If you send this text to a windows machine, the windows machine is responsible of converting 0Ah to 0Dh 0Ah otherwise viewing the text will not be much fun.Forsooth
@James: currently target system is Windows. but it may vary after some time. Any help would be appreciated.Coyle
G
4

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.

Gobbledegook answered 14/5, 2010 at 13:55 Comment(1)
Notepad is probably the only editor ever to show those files wrongBritisher
L
2

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.

Lasser answered 14/5, 2010 at 8:44 Comment(2)
@james: I am trying with bw.write("\r\n"); Once done let you guys ll k...nowCoyle
Hi buddy's.. its working ..for the time being i ll use it. If any other solution available..please let me know....Coyle
F
2

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 :)

Footless answered 14/5, 2010 at 9:16 Comment(0)
G
0

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();
    }

}
Gaptoothed answered 11/9, 2017 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.