java.io.FileNotFoundException in Java code -


this question has answer here:

i'm using code read linux swap spaces:

public void getswap() throws filenotfoundexception, ioexception     {         pattern pattern = pattern.compile("([\\/a-za-z0-9]+)[\\s]+([a-z]+)[\\s]+([0-9]+)[\\s]+([0-9]+)[\\s]+([\\-0-9]+).*");         bufferedreader reader = new bufferedreader(new filereader("/proc/swaps"));         string s = reader.readline();         while (s != null)         {             matcher matcher = pattern.matcher(s);             if (matcher.matches())             {                 system.out.println(s);                 system.out.println(matcher.group(3));                 system.out.println(matcher.group(4));             }             s = reader.readline();         }         reader.close();     } 

i want modify code return null when there not file /proc/swaps. don't want interrupt code when file missing.

you can create file object , use .exists() method check existence (and isdirectory() method make sure not directory) in advance of buffered reader creation.

then take action wanted if did not exist.

in response request code: didn't try compile this, should work so:

file file = new file("/proc/swaps"); if (!file.exists()) {     system.err.println("/proc/swaps did not exist!");     return null; } else if (file.isdirectory()) {     system.err.println("/proc/swaps directory, not file.");     return null; } 

you should wrap function in try { } catch() {} , handle exception comment can't occur since checked existence before-hand. way don't have declare function throws checked exception.


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -