无法在Java中通过套接字发送大文件

编程入门 行业动态 更新时间:2024-10-22 12:27:38
本文介绍了无法在Java中通过套接字发送大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我得到了服务器和客户端应用程序,它们在发送小文件时工作得很好,但是当我尝试发送例如700mb的电影文件时,它给了我

I got working server and client applications, they work perfect while sending small files, but when I try to send for example movie file that is 700mb over socket it gives me

Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space

我搜索了互联网,发现了一些关于发送大文件的教程,但是对它们不太了解,但我认为我的问题是写文件。

I searched the internet and found some tutorials on sending large files, but couldn't quite understand them, but I think my porblem is in writing file.

这是服务器用来编写我的文件的代码:

This is the code that server uses to write my file:

output = new FileOutputStream(directory + "/" + fileName); long size = clientData.readLong(); byte[] buffer = new byte[1024]; while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) { output.write(buffer, 0, bytesRead); size -= bytesRead; } output.close();

以下是我的客户用来发送文件的代码:

And here is the code that my client uses to send a file:

byte[] fileLength = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream(bis); dis.readFully(fileLength, 0, fileLength.length); OutputStream os = socket.getOutputStream(); //Sending size of file. DataOutputStream dos = new DataOutputStream(os); dos.writeLong(fileLength.length); dos.write(fileLength, 0, fileLength.length); dos.flush(); socket.close();

推荐答案

它为您提供 OutOfMemoryError 因为您在发送之前尝试将整个文件读入内存。这是完全100%完全没必要的。只需读取和写入块,就像在接收代码中一样。

It gives you OutOfMemoryError because you are trying to read the entire file into memory before sending it. This is 100% completely and utterly unnecessary. Just read and write chunks, much as you are doing in the receiving code.

更多推荐

无法在Java中通过套接字发送大文件

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

发布评论

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

>www.elefans.com

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