我正在尝试将文件块从服务器发送到多个客户端。当我尝试发送700mb大小的文件时,它显示"OutOfMemory java heap space“错误。我使用的是Netbeans 7.1.2版本。我还在属性中尝试了VMoption。但是仍然会发生同样的错误。我认为读取整个文件有一些问题。下面的代码可以工作到300mb。请给我一些建议。
提前感谢
public class SplitFile {
static int fileid = 0 ;
public static DataUnit[] getUpdatableDataCode(File fileName) throws FileNotFoundException, IOException{
int i = 0;
DataUnit[] chunks = new DataUnit[UAProtocolServer.singletonServer.cloudhosts.length];
FileInputStream fis;
long Chunk_Size = (fileName.length())/chunks.length;
int cursor = 0;
long fileSize = (long) fileName.length();
int nChunks = 0, read = 0;long readLength = Chunk_Size;
byte[] byteChunk;
try {
fis = new FileInputStream(fileName);
//StupidTest.size = (int)fileName.length();
while (fileSize > 0) {
System.out.println("loop"+ i);
if (fileSize <= Chunk_Size) {
readLength = (int) fileSize;
}
byteChunk = new byte[(int)readLength];
read = fis.read(byteChunk, 0, (int)readLength);
fileSize -= read;
// cursor += read;
assert(read==byteChunk.length);
long aid = fileid;
aid = aid<<32 | nChunks;
chunks[i] = new DataUnit(byteChunk,aid);
// Lister.add(chunks[i]);
nChunks++;
++i;
}
fis.close();
fis = null;
}catch(Exception e){
System.out.println("File splitting exception");
e.printStackTrace();
}
return chunks;
}发布于 2014-07-16 19:34:08
随着文件大小的增长,读取整个文件肯定会触发OutOfMemoryError。调优-Xmx1024M可能有助于临时修复,但它肯定不是正确的/可伸缩的解决方案。同样,不管你如何移动你的变量(比如在循环外创建缓冲区而不是在循环内),你迟早会得到OutOfMemoryError。不为您获取OutOfMemoryError的唯一方法是不读取内存中的完整文件。
如果您必须只使用内存,那么一种方法是将块发送到客户端,这样您就不必将所有块都保存在内存中:
而不是:
chunks[i] = new DataUnit(byteChunk,aid);执行以下操作:
sendChunkToClient(new DataUnit(byteChunk, aid));但上述解决方案的缺点是,如果在块发送之间发生错误,您可能很难尝试从错误点恢复/恢复。
像Ross Drew建议的那样,将数据块保存到临时文件中可能更好,也更可靠。
发布于 2014-07-16 18:56:33
如何创建
byteChunk = new byte[(int)readLength];在循环之外,只要重用它,而不是一遍又一遍地创建字节数组,如果它总是相同的话。
或
您可以在传入数据时将其写入到临时文件中,而不是维护巨大的数组,然后在所有数据到达时对其进行处理。
也叫
如果您多次将其用作int,那么您可能也应该在循环外部将readLength设置为int
int len = (int)readLength;Chunk_Size是一个变量,对吧?它应该以小写字母开头。
https://stackoverflow.com/questions/24778902
复制相似问题