我正在尝试读取txt文件并使用套接字从它传递数据,但看起来我在写入outputstream时缺少换行符。
我的txt文件是:
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;
}
ByteArrayOutputStream:
{“firstName”:“John”,“lastName”:“Smith”,“isAlive”: true,“age”:25,“address”:{%“streetAddress”:“21 2nd 街道“,”城市“:”纽约“,”州“:”纽约“,
“postalCode”:“10021-3100”}}
System.getProperty("line.separator");
修改
baos
帮助我使用新行,但我仍然在System.out.println(new String(baos.toByteArray()));
input.csv
1,[103.85,1.28992],[103.89,1.294],[103.83,1.216]
2,[103.5,1.292],[103.9,1.4],[103.3,1.21]
3,[103.6,1.291],[103.6,1.39],[103.3,1.29]
答案 0 :(得分:0)
使用以下
重写代码while (scanner.hasNextLine()){
out.writeUTF(scanner.nextLine()+"\n");
}
答案 1 :(得分: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;
}