我有这个代码压缩文件夹,但是当我压缩大文件夹(10GB)时,出现内存错误。它适用于1GB左右的文件夹。压缩 - java.lang.OutOfMemoryError:Java堆空间
可能是一些内存泄漏,但在我的代码泄漏?我怎样才能解决这个问题?
谢谢。
这是错误:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:56)
Caused by: java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2882)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:100)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:572)
at java.lang.StringBuilder.append(StringBuilder.java:203)
at java.io.UnixFileSystem.resolve(UnixFileSystem.java:93)
at java.io.File.<init>(File.java:207)
at java.io.File.listFiles(File.java:1056)
at Zipper.addDir(Zipper.java:27)
at Zipper.addDir(Zipper.java:32)
at Zipper.addDir(Zipper.java:32)
at Zipper.addDir(Zipper.java:32)
at Zipper.addDir(Zipper.java:32)
at Zipper.addDir(Zipper.java:32)
at Zipper.addDir(Zipper.java:32)
at Zipper.addDir(Zipper.java:32)
at Zipper.addDir(Zipper.java:32)
at Zipper.zipDir(Zipper.java:17)
at Schedule.runBackup(Schedule.java:128)
at Machine.runBackup(Machine.java:108)
at Person.main(Person.java:51)
这是代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Zipper {
static void zipDir(String zipFileName, String dir) throws Exception {
File dirObj = new File(dir);
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
addDir(dirObj, out);
out.close();
} catch(Exception e) {
JFrame frame = new JFrame();
JOptionPane.showMessageDialog(frame, e.getMessage() + ". Is settings.xml correct?");
}
}
static void addDir(File dirObj, ZipOutputStream out) throws IOException {
try {
File[] files = dirObj.listFiles();
byte[] tmpBuf = new byte[1024];
for (int i = 0; i < files.length; i++) {
try {
if (files[i].isDirectory()) {
addDir(files[i], out);
continue;
}
FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
out.putNextEntry(new ZipEntry(files[i].getAbsolutePath().replace(File.separatorChar,'/')));
int len;
while ((len = in.read(tmpBuf)) > 0) {
try {
out.write(tmpBuf, 0, len);
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
out.closeEntry();
in.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
什么是您的jdk版本?我问的原因是在jdk 1.4中有一个[JIRA](http://bugs.sun.com/bugdatabase/view_bug.do;:YfiG?bug_id=4705373)。 – CoolBeans