我正在尝试使用Socket读取txt文件并从其中传递数据,但在编写输出流时,我似乎缺少了换行符。
我的txt文件是:
{
"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 21“,"city":"New York","state":"NY", "postalCode":"10021-3100“}
Scaner:

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()));

发布于 2017-03-07 16:07:08
看来.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;
}发布于 2017-03-06 08:42:58
使用下面的代码重写代码
while (scanner.hasNextLine()){
out.writeUTF(scanner.nextLine()+"\n");
}https://stackoverflow.com/questions/42620309
复制相似问题