Java新手。
我的代碼是這樣的:
try {
String message = new String ( Files.readAllBytes(Paths.get("src/test.txt")));
// ... other operations
} catch (IOException e) {
e.printStackTrace();
}
我需要做些什么來防止記憶體泄漏嗎?我想任何檔案流都應該關閉,但我找不到辦法,因為我正在使用Paths.
謝謝!
uj5u.com熱心網友回復:
讓我們看一下源代碼:
public static byte[] readAllBytes(Path path) throws IOException {
try (SeekableByteChannel sbc = Files.newByteChannel(path);
InputStream in = Channels.newInputStream(sbc)) {
if (sbc instanceof FileChannelImpl)
((FileChannelImpl) sbc).setUninterruptible();
long size = sbc.size();
if (size > (long) MAX_BUFFER_SIZE)
throw new OutOfMemoryError("Required array size too large");
return read(in, (int)size);
}
}
此方法確保在讀取所有位元組或引發 I/O 錯誤或其他運行時例外時關閉檔案。因此,此方法在讀取檔案后關閉輸入流。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417472.html
標籤:
