我有一个守护程序,它读取文件的内容,然后将其压缩并将其写入较小的 .tar.gz 文件。
出于某种原因,Java 继续分配内存,即使在我释放(或我认为我已经)所有使用的内存之后。我的代码/推理有什么问题?
FileOutputStream fos = null;
GZIPOutputStream gzipos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
while (true) {
if (f.length() != 0) {
if (outputfile == null) {
outputfile = outputfileroot + "_" + outputPart + ".tar.gz";
fos = new FileOutputStream(outputfile);
gzipos = new GZIPOutputStream(fos);
osw = new OutputStreamWriter(gzipos);
bw = new BufferedWriter(osw);
}
else if (new File(outputfile).length() > maxLengthOutputFile) {
bw.flush();
osw.flush();
gzipos.flush();
fos.flush();
bw.close();
osw.close();
gzipos.close();
fos.close();
bw = null;
osw = null;
gzipos = null;
fos = null;
System.gc();
System.out.println("Finished writing " + outputfileroot + "_" + outputPart + ".tar.gz");
outputfile = outputfileroot + "_" + ++outputPart + ".tar.gz";
fos = new FileOutputStream(outputfile);
gzipos = new GZIPOutputStream(fos);
osw = new OutputStreamWriter(gzipos);
bw = new BufferedWriter(osw);
}
/**
* Read the entire file
*/
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
// will send the content to another thread, so I need to read it line by line
bw.write(line + "\r\n");
}
br.close();
br = null;
bw.flush();
/**
* Empty it
*/
FileWriter fw = new FileWriter(f);
fw.write("");
fw.flush();
fw.close();
fw = null;
}
Thread.sleep(1000);
}