0

I'm trying to read txt file and pass data from it using Sockets, but looks like I'm missing newlines while writing to outputstream.

My txt file is:

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  }
}

ByteArrayOutputStream:

{ "firstName": "John", "lastName": "Smith", "isAlive": true, "age": 25, "address": {% "streetAddress": "21 2nd Street", "city": "New York", "state": "NY",
"postalCode": "10021-3100" }}


Scaner: enter image description here

private byte[] readFile(String path) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);

    File file = new File(path);
    Scanner scanner = new Scanner(file);

    while (scanner.hasNextLine()){
        out.writeUTF(scanner.nextLine());
    }

    byte[] bytes = baos.toByteArray();
    return bytes;
}

EDIT:

System.getProperty("line.separator"); 

Helped me with new lines, but I still get some invalid characters in baos

System.out.println(new String(baos.toByteArray()));

enter image description here

Little Fox
  • 1,212
  • 13
  • 39
  • 4
    `nextLine()` reads a line without the new line character – Jens Mar 06 '17 at 07:59
  • Don't reinvent the wheel: http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllBytes-java.nio.file.Path-, http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#copy-java.nio.file.Path-java.io.OutputStream- – JB Nizet Mar 06 '17 at 08:02

2 Answers2

0

Rewrite the code using below

while (scanner.hasNextLine()){
        out.writeUTF(scanner.nextLine()+"\n");
    }
  • The new line character isn't \n on every system so it's better to use System.getProperty("line.separator") – dsp_user Mar 06 '17 at 10:56
0

Looks like .flush() helped me to clear invalid characters...

private byte[] readFile(String path) throws IOException {

    DataOutputStream out = new DataOutputStream(socket.getOutputStream());

    File file = new File(path);
    Scanner scanner = new Scanner(file);

    while (scanner.hasNextLine()){
        out.writeUTF(scanner.nextLine() + System.getProperty("line.separator"));
    }

    byte[] bytes = out.toByteArray();
    out.flush();
    return bytes;
}

What is the purpose of flush() in Java streams?

Community
  • 1
  • 1
Little Fox
  • 1,212
  • 13
  • 39