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();
}
ADTC
  • 8,999
  • 5
  • 68
  • 93
Manu
  • 3,179
  • 23
  • 57
  • 69

6 Answers6

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.

Roman Cherepanov
  • 1,639
  • 2
  • 24
  • 44
James B
  • 3,692
  • 1
  • 25
  • 34
  • 6
    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`). – Jesper May 14 '10 at 11:43
  • 1
    @Jesper - thanks, I've updated it accordingly, I knew it was there or thereabouts – James B May 14 '10 at 12:20
  • 1
    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`)? – ADTC Dec 12 '13 at 07:45
  • 1
    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. – ADTC Dec 12 '13 at 07:51
  • 2
    @ADTC nothing is ever automgaically converted - in this example you're writing raw byte values into a file – James B Dec 13 '13 at 10:11
  • Why don't you concatenate inline? Like this: bw.write(rs.getString(1)==null? "":rs.getString(1) + "\r\n"); – Laszlo Lugosi Jul 27 '16 at 14:28
  • 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 1 – user3286012 Oct 05 '17 at 18:20
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.

nc3b
  • 15,562
  • 5
  • 51
  • 63
  • i am not getting you. could you please explain it. – Manu May 14 '10 at 08:38
  • 1
    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. – nc3b May 14 '10 at 08:43
  • @James: currently target system is Windows. but it may vary after some time. Any help would be appreciated. – Manu May 14 '10 at 08:43
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.

Axel
  • 13,939
  • 5
  • 50
  • 79
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.

Vaishak Suresh
  • 5,735
  • 10
  • 41
  • 66
  • @james: I am trying with bw.write("\r\n"); Once done let you guys ll k...now – Manu May 14 '10 at 09:34
  • Hi buddy's.. its working ..for the time being i ll use it. If any other solution available..please let me know.... – Manu May 14 '10 at 09:47
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 :)

rompetroll
  • 4,781
  • 2
  • 37
  • 50
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();
    }

}