I want to remove the throws FileNotFoundException from the method head and put it into it.
public static String[] read(String file) throws FileNotFoundException {
But then I can't access in (the scanner) anymore! How to handle that?
public static String[] read(String file) {
try {
Scanner in = new Scanner(new FileReader(file));
}
catch (Exception e) {
}
// ...
in.close();
// ...
}
CodePudding user response:
Just use try-with-resources so you dont have to worry about closing the scanner object.
try (Scanner in = new Scanner(new FileReader(file))) {
//Your code
}
catch (Exception e) {
}
CodePudding user response:
you can use try with ressource, that permit to close automaticaly your in.
like that
Scanner in ;
try ( in = new Scanner(new FileReader(file))) {
}
catch (Exception e) {
}
CodePudding user response:
The variable in is out of scope outside the try block. You can either do this:
public static String[] read(String file) {
Scanner in = null;
try {
in = new Scanner(new FileReader(file));
}
catch (Exception e) {
}
finally() {
in.close();
}
// ...
}
Or better yet, try with resources
public static String[] read(String file) {
try (Scanner in = new Scanner(new FileReader(file))){
String line = in.nextLine();
// whatever comes next
}
catch (Exception e) {
}
// right here, the scanner object will be already closed
return ...;
}
CodePudding user response:
The in variable is locally scoped to the try block. You can either declared the variable before the try block, or close in within the try block. There's not much use in closing it if it never successfully opened.
