gpt4 book ai didi

java - Java中使用Scanner时如何减少内存泄漏?

转载 作者:行者123 更新时间:2023-12-02 04:37:12 26 4
gpt4 key购买 nike

我使用扫描仪读取许多日志文件(约 100 个文件),每个日志文件约 120mb,超过 1,000,000 行。用于读取日志文件的内存不断增加并导致内存过载。如何防止这种情况发生?这是我的代码:

File file = processing.poll(); // processing is a queue.
Scanner sc = new Scanner(file);
String line;
int lineCount = 0;
while (sc.hasNextLine()) {
line = sc.nextLine();
}
sc.close();

谢谢你!!

P/S:内存增加缓慢,每个处理的文件约1mb,但我会将这段代码推送到服务器,将来会有无数的文件。

最佳答案

我建议您使用 try-with-resources close Scanner并释放文件句柄。另外,您可以限制 line 的范围我认为你的意思是增加 lineCount 。比如,

int lineCount = 0;
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
lineCount++;
}
}

或者,您可以使用 finally block 状

int lineCount = 0;
Scanner sc = new Scanner(file);
try {
while (sc.hasNextLine()) {
String line = sc.nextLine();
lineCount++;
}
} finally {
sc.close();
}

关于java - Java中使用Scanner时如何减少内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30610313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com