我有工作服务器和客户端应用程序,它们在发送小文件时工作得很好,但是当我尝试通过套接字发送例如 700mb 的电影文件时,它给了我
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space
我在互联网上搜索并找到了一些有关发送大文件的教程,但不太理解它们,但我认为我的问题在于写入文件。
这是服务器用来写入我的文件的代码:
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();
这是我的客户用来发送文件的代码:
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%完全没有必要的。只需读取和写入块,就像您在接收代码中所做的那样。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)