将大文件客户端发送到服务器 [英] Sending large files Client to Server
问题描述
我正在尝试将文件发送到服务器.我可以处理小于100mb的文件.否则我用光了堆.因此,我重新制作了它,但实际上无法使其正常工作.除了读取卡在bis.read(buffer)中的最后一个数据外,我还可以工作,因为它不知道文件何时结束.因此,我尝试发送每个段的长度,以便bufferedInputStream知道何时停止读取.
I'm trying to send files to my server. I got it working with files smaller than 100mb. Otherwise I ran out of heap. So I remade it but can't really get it to work. I also got the to work except for reading the last data I get stuck in bis.read(buffer) because it didn't know when the file ended. So I tried to send the length of each segment so that the bufferedInputStream know when to stop reading.
你知道怎么了吗?
发件人代码:
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[2048];
Integer bytesRead = 0;
BufferedOutputStream bos = new BufferedOutputStream(clientSocket.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(fis);
while ((bytesRead = bis.read(buffer)) > 0) {
objectOutStream.writeObject(bytesRead);
bos.write(buffer, 0, bytesRead);
}
System.out.println("Sucess sending file");
接收器(服务器):
fileName = request.getFileName();
int size = (int) request.getSize();
BufferedInputStream bis = new BufferedInputStream(clientSocket.getInputStream());
FileOutputStream fos = new FileOutputStream(fileName);
int totalBytesReceived = 0;
int blockSize = 0;
while (totalBytesReceived < size) {
Object o = ois.readObject();
if (!(o instanceof Integer)) {
System.out.println("Something is wrong");
}
blockSize = (Integer) o;
buffer = new byte[blockSize];
bis.read(buffer);
totalBytesReceived += blockSize;
fos.write(buffer, 0, blockSize);
}
System.out.println("File succes");
推荐答案
您在服务器端的阅读代码应与客户端相同.
Your reading code on the server side should look the same as on the client side.
// copy from bis to bos, using a buffer.
for(int len; (len = bis.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
在您想要的客户端上
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filename));
BufferedOutputStream bos = new BufferedOutputStream(clientSocket.getOutputStream());
在所需的服务器端.
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filename));
完成后想要
bos.close();
bis.close();
如果要使用ObjectOutputStream(建议不要使用),则只需使用此流,而不必使用流的混合.
If you are going to use an ObjectOutputStream (and I suggest you don't) you need to use only this stream, not a mixture of streams.
这篇关于将大文件客户端发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!