2 回答
TA贡献1921条经验 获得超9个赞
文件是可序列化的,所以我建议您应该尝试直接通过 ObjectOutputStream / ObjectInputStream 发送它。
例如在服务器端:
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
...
out.writeObject(yourFileObject);
在客户端:
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
...
File receivedFile = null;
try {
receivedFile = (File) in.readObject();
}
catch (IOException e) {
...
}
TA贡献1873条经验 获得超9个赞
我不完全确定为什么会发生这种情况,但您不应该使用DataInputStream
which “让应用程序读取原始 Java 数据类型”,而InputStreamReader
which “是从字节流到字符流的桥梁”。
此外,您可以将该阅读器包装成一个BufferedReader让您逐行阅读的内容,您最终会得到类似
try (BufferedReader reader=new BufferedReader(new InputStreamReader(inStream, UTF8));
PrintWriter writer = new PrintWriter(file)) {
reader.lines().forEach(writer::println);
}
上传,或
try (PrintWriter writer = new PrintWriter(outStream)) {
Files.lines().forEach(writer::println);
}
下载。
添加回答
举报