views:

41

answers:

3
+4  A: 

You need to somehow deal with IOException, either catching it or throwing from main. For a simple program, throwing is probably fine:

public static void main(String[] args) throws IOException
Matthew Flaschen
To be specific put a try/catch around the code or indicate that main throws IOException. You should do development in an IDE (such as Eclipse (which is free)). The benefit of this is that an IDE will give you warnings/errors and offer solutions to problems such as this.
Syntax
It worked, But why I need to throw an exception if I've already created the file?
MoonStruckHorrors
You're saying your program *can* throw an exception. Most of the time it won't, but there are all sorts of possible IO errors. For instance, imagine if you ran out of disk space.
Matthew Flaschen
+2  A: 

You're not dealing with IOException. You need to either catch it or throw it explicitly.

try{
  // Your code
}catch(IOException e){
  // Deal with IOException
}

or

public static void main(String[] args) throws IOException{
  // Your code
}

This is all a consequence of Java having checked exceptions, of which IOException is one.

For your purposes, the second is probably fine since an IO failure can't really be recovered from. In larger programs, you'll almost certainly want to recover from transient IO failures and thus the first would be more appropriate.

Kevin Montrose
+1  A: 

You need to use a try/catch block, handling exceptions that are declared as thrown in the methods you are using. It would be worthwhile to read up on exception handling.

akf