使用FileInputStream / ObjectOutputStream发送大文件

编程入门 行业动态 更新时间:2024-10-22 20:31:08
本文介绍了使用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发送大文件

本文发布于:2023-11-25 17:41:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630716.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:大文件   FileInputStream   ObjectOutputStream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!