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(); }
'\r' is the representation of the special character CR (carriage return), it moves the cursor to the beginning of the line. '\n'(line feed) moves the cursor to the next line . On windows both are combined as \r\n to indicate an end of line (ie, move the cursor to the beginning of the next line).
A line feed means moving one line forward. The code is \n . A carriage return means moving the cursor to the beginning of the line. The code is \r .
\n is a line feed (LF) character, character code 10. \r is a carriage return (CR) character, character code 13. What they do differs from system to system. On Windows, for instance, lines in text files are terminated using CR followed immediately by LF (e.g., CRLF).
\t Insert a tab in the text at this point. \b Insert a backspace in the text at this point. \n Insert a newline in the text at this point.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With