我正在尝试读取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“}}
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()));
'nextLine()读取'没有新行字符的行 – Jens
不要重新创建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- –