2017-03-06 71 views
0

我正在尝试读取txt文件并使用套接字传递数据,但看起来像在写入outputstream时缺少新行。写入到ByteArrayOutputStream时缺少NewLines

我的txt文件是:

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

ByteArrayOutputStream:

{ “名字”: “约翰”, “姓氏”: “史密斯”, “的IsAlive”: 真,“年龄”:25,“地址”:{%“streetAddress”:“21 2nd Street”,“city”:“New York”,“state”:“NY”,
“postalCode”:“ 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; 
} 

编辑:

System.getProperty("line.separator"); 

帮我新的生产线,但我仍然得到一些无效字符baos

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

enter image description here

+4

'nextLine()读取'没有新行字符的行 – Jens

+0

不要重新创建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- –

回答

0

看起来像.flush()帮我清除无效字符重写代码...

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?

0

使用下面

while (scanner.hasNextLine()){ 
     out.writeUTF(scanner.nextLine()+"\n"); 
    } 
+0

新行字符在每个系统上都不是\ n,所以它是更好地使用System.getProperty(“line.separator”) –