Will the java process keeps the file open if the Scanner was not closed? -



Will the java process keeps the file open if the Scanner was not closed? -

i found out java process throws error:

caused by: java.net.socketexception: many open files

i understand rectified increasing open file limits in unix, however, want find out why files not beingness closed java process in first place.

i checked source-code , found below snippet used read info files.

string content = new scanner(new file("../../example/test.txt"), "utf-8").usedelimiter("\\a").next();

i assume here problem scanner not beingness closed after reading? issue? or because scanner object not created, doesn't need closed?

i assume here problem scanner not beingness closed after reading?

this culprit. scanner can closed implicitly if available garbage collection. however, since impossible predict when garbage collector run, should never rely on this. instead, should explicitly close scanner when finished it. means should follow pattern:

scanner scan = null; seek { scan = new scanner(file); string token = scan.next(); // token } grab (exception ex) { // print out error message } scan.close(); }

of course, depending on exact needs, might in method propagates exceptions declaring throws clause. main thought need clause somewhere ensure scanner closed whether or not exception ever thrown.

note java 7 introduced "try resources" makes much easier manage kind of situation. if using java 7, suggest this.

java

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -