0

My groovy program creates a csv that is has \n for new line. But the customer wants \r\n as they run windows.

I understand that this question is answered a tonne of time on SO including here How to remove line breaks from a file in Java?

This script here does not replace \n with \r\n. The \n just stays on

    newline = System.getProperty("line.separator");
    for (int i = 0; i < dataContext.getDataCount(); i++) {
        InputStream is = dataContext.getStream(i);
        Properties props = dataContext.getProperties(i);

        reader = new BufferedReader(new InputStreamReader(is));
        outData = new StringBuffer();
        lineNum = 0;

        while ((line = reader.readLine()) != null) {
            line.replace(newline, "\r\n")
            outData.append(line);


        }
        is = new ByteArrayInputStream(outData.toString().getBytes("UTF-8"));

        dataContext.storeStream(is, props);
    }
Community
  • 1
  • 1
lonelymo
  • 3,972
  • 6
  • 28
  • 36
  • 1
    As a side note, you should always close() your streams in a finally { ... } block. – lance-java Apr 23 '15 at 13:05
  • If you want to convert a file from a second command use something like dos2unix. But if you want to generate the file with the proper line separator you can simply set a proper line separator in the script that generates the file itself simply use: System.setProperty("line.separator", "\r\n") – user1708042 Apr 24 '15 at 14:15

1 Answers1

3

You are reading the file a line at the time by using readLine - this already removes the line ending for you.

What you need to do is read the lines one at a time as you do now - then append \r\n in between each line, not replace.

   while ((line = reader.readLine()) != null) {
        outData.append(line);
        outData.append("\r\n");
    }
Tim B
  • 40,716
  • 16
  • 83
  • 128
  • Thanks, my bad. Now I only have \n at the end of each line. I write the file into the windows file system as a .csv and open it with SublimeText. Here I try to search for '\r\n' and it returns nothing. – lonelymo Apr 23 '15 at 13:59