【发布时间】:2017-07-26 00:13:04
【问题描述】:
我正在尝试读取 txt 文件并使用套接字从中传递数据,但看起来我在写入输出流时缺少换行符。
我的txt文件是:
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
}
}
字节数组输出流:
{ "firstName": "John", "lastName": "Smith", "isAlive": 真,“年龄”:25,“地址”:{%“街道地址”:“21 2nd 街道”,“城市”:“纽约”,“州”:“纽约”,
"邮政编码": "10021-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()读取一行没有换行符
标签: java