How to close scanner class if we did not create reference variable for object so how to avoid resource leak warning message

北城以北 提交于 2021-02-07 20:13:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!