本文介绍了使用FileInputStream / ObjectOutputStream发送大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的作业需要帮助,非常感谢任何帮助。我可以毫无问题地发送小文件。但是当我尝试发送时,假设一个1GB的文件字节数组发送OutOfMemoryError,所以我需要一个更好的解决方案来将文件从服务器发送到客户端。如何改进此代码并发送大文件,请帮助我。
I need help on my homework, any help will be much appreciated. I can send small files without a problem. But when i try to send let’s say a 1GB file byte array sends OutOfMemoryError so i need a better solution to send file from server to client. How can i improve this code and send big files, please help me.
服务器代码:
FileInputStream fis = new FileInputStream(file);
byte[] fileByte = new byte[fis.available()]; //This causes the problem.
bytesRead = fis.read(fileByte);
oos = new ObjectOutputStream(sock.getOutputStream());
oos.writeObject(fileByte);
客户代码:
ois = new ObjectInputStream(sock.getInputStream());
byte[] file = (byte[]) ois.readObject();
fos = new FileOutputStream(file);
fos.write(file);
推荐答案
以下是我解决的方法:
客户代码:
bis=new BufferedInputStream(sock.getInputStream());
fos = new FileOutputStream(file);
int n;
byte[] buffer = new byte[8192];
while ((n = bis.read(buffer)) > 0){
fos.write(buffer, 0, n);}
服务器代码:
bos= new BufferedOutputStream(sock.getOutputStream());
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int n=-1;
byte[] buffer = new byte[8192];
while((n = bis.read(buffer))>-1)
bos.write(buffer,0,n);
这篇关于使用FileInputStream / ObjectOutputStream发送大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!