Reputation: 11
This is my method, I want to know if there is possibility for memory leak? If there is what should I do to?
private byte[] getNewContent(String filePath, int position, int size) throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
Upvotes: 1
Views: 51
Reputation: 24229
yes, there is resource leak
if some exception happens in seek/read methods - file will not be closed, it is better to use try-with-resources idiom:
private byte[] getNewContent(String filePath, int position, int size) throws IOException {
try (RandomAccessFile file = new RandomAccessFile(filePath, "r")) {
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
return bytes;
}
}
this way file will be closed no matter what
Upvotes: 1