问题
How to close scanner class if we did not create object for it to avoid warning messages stating unassigned closable value, resource leak?
As I need to get input only once from user, I did not create reference variable for object Scanner class.
My declaration to get input
int num = new Scanner(System.in).nextInt();
回答1:
i did not created object for Scanner class
yes, you did: new Scanner(System.in)
In case, you are allowed to use try-with-resource:
try(Scanner sc=new Scanner(System.in)){
int num = sc.nextInt();
/* TO DO */
}
OR, just use the .close():
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
sc.close();
回答2:
Or you can use try/finally:
Scanner sc = null;
try
{
sc = new Scanner(System.in);
int num = sc.nextInt();
}
finally
{
if(sc!=null)
{
sc.close();
}
}
回答3:
There is no way with your syntax to close the scanner object.
Only one way I can think of right now is, if Scanner would not have been a final class, we could created a class which extends it says ScannerAutoClose and declare/override a finalize method for it and close the object in it using this.close(). The finalize
method would have been called at the time of garbage collection so it get's closed automatically. But since Scanner is final class, this is out of the picture.
来源:https://stackoverflow.com/questions/52050299/how-to-close-scanner-class-if-we-did-not-create-reference-variable-for-object-so