无法在Java中通过套接字发送大文件 [英] Can't send large files over socket in 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中通过套接字发送大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!