Закрывающая скобка в блоке catch
не на своем месте. Переместите его так, чтобы он был ниже System.out.println("Error");
.
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) { // <-- from here
System.out.println("Error");
// or even better
e.printStackTrace();
} // <-- to here
}
В целях защитного программирования (по крайней мере, до Java 7) вы всегда должны закрывать ресурсы в блоке finally
:
public static void main(String[] args) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {}
}
// or if you're using Google Guava, it's much cleaner:
Closeables.closeQuietly(in);
}
}
Если вы используете Java 7, вы можете воспользоваться преимуществами автоматического управления ресурсами через try
-with-resources :
public static void main(String[] args) {
try (BufferedReader in = new BufferedReader(new FileReader("hello.txt"))) {
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}