How to add newline character to a byte array in Java?

18,287

Solution 1

New line character is OS dependant, you should retrieve it calling System.getProperty("line.separator")

Or better, if you are writing a textfile you should use BufferedWriter which has the method newLine() to write the line separator independent of the OS

Solution 2

You can prove it works by reading and printing the file.

import java.io.*;


public class Main {
    public static void main(String args[]) {
        String filename = "newfile.txt";
        byte[] cities = {'n', 'e', 'w', 'y', 'o', 'r', 'k', '\n', 'd', 'c'};
        FileOutputStream outfile = null;
        try {
            outfile = new FileOutputStream(filename);
            outfile.write(cities);
            outfile.close();

            BufferedReader in = new BufferedReader(new FileReader(filename));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        byte[] cities2 = {'n', 'e', 'w', 'y', 'o', 'r', 'k', 'd', 'c'};
        outfile = null;
        try {
            outfile = new FileOutputStream(filename);
            outfile.write(cities2);
            outfile.close();

            BufferedReader in = new BufferedReader(new FileReader(filename));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

Test

newyork
dc
newyorkdc
Share:
18,287
Chaipau
Author by

Chaipau

Updated on June 04, 2022

Comments

  • Chaipau
    Chaipau almost 2 years

    The following piece of code tries to introduce a newline character into a byte array and write the byte array to a file.

    import java.io.*;
    public class WriteBytes {
        public static void main(String args[]) {
            byte[] cities = { 'n', 'e', 'w', 'y', 'o', 'r', 'k', '\n', 'd', 'c' };
            FileOutputStream outfile = null;
            try {
                outfile = new FileOutputStream("newfile.txt");
                outfile.write(cities);
                outfile.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Contents of the newfile were: newyorkdc

    What I expected was:
    newyork
    dc

    I tried to typecast '\n' to (byte)'\n' but to no avail.

    Solution: Change the array initialization to

    byte[] cities = { 'n', 'e', 'w', 'y', 'o', 'r', 'k', '\r','\n', 'd', 'c' };
    

    I had used Notepad++ to view the contents of the file.I suppose it suppressed the newline character but accepted the carriage return followed by newline combination.

    • T.J. Crowder
      T.J. Crowder over 7 years
      What you have is correct (I've double-checked by running that code locally). The issue must be in how you're looking at the result.
    • Chaipau
      Chaipau over 7 years
      @T.J.Crowder : I didn't understand what you meant by how I am looking at the result.Isn't it suppose to write the contents of the array in a newline after '\n'?
    • T.J. Crowder
      T.J. Crowder over 7 years
      I'm saying that your code worked correctly, so if you think the contents of your file are newyorkdc, you're mistaken. Either you were looking at an old file that wasn't written by this code, or the tool you looked at it with hid the \n from you. When I ran your code, unmodified, I got a file with the bytes 6e 65 77 79 6f 72 6b 0a 64 63 in it. Note that the 8th byte is a newline (0a). When I do cat newfile.txt, I see the newline in the result (I'm using *nix). The code is fine.
    • T.J. Crowder
      T.J. Crowder over 7 years
      I suggest deleting the question while you investigate further, as it cannot be answered.
    • chris
      chris over 7 years
      Just try this: { 'n', 'e', 'w', 'y', 'o', 'r', 'k', '\r', '\n', 'd', 'c' }; (\r added). Maybe this looks better in your editor.
    • Chaipau
      Chaipau over 7 years
      @T.J.CrowderThanks for helping out.I used Notepad++ to view the file.Probably it skipped the newline character.
    • Egl
      Egl over 7 years
      I agree T.J. Crowder. The code is ok writing the newline char
    • xro7
      xro7 over 7 years
    • T.J. Crowder
      T.J. Crowder over 7 years
      Side note: Although the code will work and doesn't have a problem writing the newline to the file, I do suggest using try-with-resources rather than manually closing the stream: pastebin.com/51dZefZE