0

I am creating a file for a rigid system that doesn't like \r\n at the end of the file. But while creating the file, java adds it automatically.

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class FileTest {

    public static void main(String[] args) throws Exception {
        String fileText = "a\r\nb";
        String filePath = "/log/engines/Testfile.txt";


        FileOutputStream out = null;
        ByteArrayOutputStream byteOut = null;
        try {
            out = new FileOutputStream( filePath);
            byteOut = new ByteArrayOutputStream();

            char[] charArr = fileText.toCharArray();
            for( int i=0; i<charArr.length; i++) {
                byteOut.write( charArr[i]);
//              out.write( charArr[i]);
            }
            byteOut.writeTo( out);
            System.out.println( "Last Char in File =" +charArr[charArr.length-1] +"=" +(int)charArr[charArr.length-1]);
        } finally {
            if (byteOut != null) {
                byteOut.close();
            }
            if (out != null) {
                out.close();
            }
        }           
    }
}

The binary of this file is as below -

610d 0a62 0d0a == (a\r \nb \r\n)

0d = "\r"
0a = "\n"

I am fine with the first "\r\n" which I am adding, but not the last one that gets added by itself. Appreciate any help.

  • Do you have to use a ByteArrayOutputStream? – Yoland Gao Jan 28 '16 at 21:14
  • 7
    are you opening the file in another editor after the fact? (neither FileOutputStream nor ByteArrayOutputStream will add the problem characters) – jtahlborn Jan 28 '16 at 21:15
  • Running the code you supplied (only change: value of filePath) on a Windows machine with Java 1.7.0_60 outputs `Last Char in File =b=98`. When I open the Testfile.txt in a text editor, it does not show any newline (\r\n) after the "b". – reowil Jan 28 '16 at 21:32
  • Running your code on a Mac `hexdump Testfile.txt` outputs `61 0d 0a 62` – Daniel Jan 28 '16 at 22:02
  • When I run this program in Windows and I see correct values in the hex viewer (https://hexed.it/?hl=en), but when I view the file using vi, and Escape followed by :%!xxd, it displays \r\n codes at end. – Booshan Rengachari Jan 28 '16 at 22:54
  • @Daniel I get the following output if I use hexdump. Sorry, I don't understand this output. #hexdump Testfile.txt 0000000 0d61 620a 0000004 – Booshan Rengachari Jan 28 '16 at 23:02
  • 1
    so the answer is that vi is modifying your doc. (http://stackoverflow.com/questions/1050640/vim-disable-automatic-newline-at-end-of-file) – jtahlborn Jan 29 '16 at 15:58
  • Ah, you're on a different system so the big-endianness appears to be different. tryin hexdump -C instead, it should be more clear. – Daniel Jan 29 '16 at 19:15

0 Answers0