【发布时间】:2012-07-12 01:25:38
【问题描述】:
我有工作的服务器和客户端应用程序,它们在发送小文件时工作完美,但是当我尝试通过套接字发送例如 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();
【问题讨论】:
-
你能做的最好的事情就是像这样运行你的程序stackoverflow.com/questions/542979/… 然后你可以使用 jvisualvm 来分析它。
-
我认为您的问题是您试图将 X MB 的内容查找到 Y MB 内存中,其中 X > Y。如果这是真的,您如何编写该文件并不重要。这就是异常告诉你的。
-
你想一口气吃掉一个大西瓜,所以你死定了。尝试读取一小段文件并将其发送出去并重复操作。