【发布时间】:2014-09-29 17:58:10
【问题描述】:
我已经尝试了几天,但没有成功。
我想通过套接字客户端/服务器发送文件。唯一的区别是:我想发送一个包含文件字节的对象。
所以客户端加载一个文件,读取1024字节的块,将它们存储在一个对象中,然后将对象发送到服务器。由于文件可能大于 1024 字节,我想重复发送对象,但在其中存储不同的字节(当缓冲区读取它时)。在服务器上,我想组合字节数组并将其保存为文件。
我使用 1024 的原因是因为我想避免任何类型的内存不足错误,如果文件大小为 4 GB。
我尝试在客户端上执行以下操作:
File file = new File("C:\\test\\test.txt");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
byte[] bytes = new byte[1024];
FileTest ft = new FileTest();
ft.setName("Testing");
int counttest = 1;
while (bis.read(bytes) > 0) {
ft.setCounttest(counttest);
ft.setBytes(bytes);
oos.writeObject(ft);
counttest += 1;
}
在服务器上:
int bufferSize = socket.getReceiveBufferSize();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\test\\test2.txt"));
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
byte[] bytes = new byte[bufferSize];
while (true) {
FileTest ft = (FileTest) ois.readObject();
if (ft != null) {
System.out.println(ft.getName());
bos.write(ft.getBytes());
}
}
所以我测试了发送一个带有数字序列的 txt 文件,而服务器生成的 test2.txt 文件只输出了前 1024 个字节块重复了两次。此外,counttest 整数在服务器中接收时永远不会增加。
知道如何做到这一点吗?
提前致谢。
【问题讨论】:
-
永远不要丢弃
bis.read(bytes)实际读取的字节数,因为它很可能通过套接字读取的字节数少于完整字节数。 -
如果一次读取大块字节,则不需要缓冲流。