文件使用完毕后关闭文件

This commit is contained in:
skipify 2022-07-15 09:19:20 +08:00
parent 3b22a015a3
commit a43733cb97
2 changed files with 9 additions and 1 deletions

View File

@ -35,6 +35,8 @@ public class SearcherTest {
String ip = "1.2.3.4";
long sTime = System.nanoTime();
String region = searcher.search(ip);
//一定关闭
searcher.close();
long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
} catch (Exception e) {
@ -81,6 +83,7 @@ public class SearcherTest {
String ip = "1.2.3.4";
long sTime = System.nanoTime();
String region = searcher.search(ip);
searcher.close();
long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
} catch (Exception e) {
@ -127,6 +130,7 @@ public class SearcherTest {
String ip = "1.2.3.4";
long sTime = System.nanoTime();
String region = searcher.search(ip);
//此处可以不调用 searcher.close() 因为使用了newWithBuffer没有打开文件
long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
} catch (Exception e) {

View File

@ -163,6 +163,7 @@ public class Searcher {
handle.seek(0);
final byte[] buff = new byte[HeaderInfoLength];
handle.read(buff);
handle.close();
return new Header(buff);
}
@ -177,8 +178,10 @@ public class Searcher {
final byte[] buff = new byte[len];
int rLen = handle.read(buff);
if (rLen != len) {
handle.close();
throw new IOException("incomplete read: read bytes should be " + len);
}
handle.close();
return buff;
}
@ -193,9 +196,10 @@ public class Searcher {
final byte[] buff = new byte[(int) handle.length()];
int rLen = handle.read(buff);
if (rLen != buff.length) {
handle.close();
throw new IOException("incomplete read: read bytes should be " + buff.length);
}
handle.close();
return buff;
}