0
import javax.swing.*;
import java.io.*;
import java.util.*;
class Buns {
    public static void main(String[] args) {
        File f= new File("Buns.dat");
            f.createNewFile();
   }
}

This program raises an IOException on the createNewFile call can anyone tell me why this could be happening?

Kevin K
  • 81
  • 7
  • Copied the code over and it worked fine.. – christopher Mar 02 '13 at 08:20
  • What's the message of the exception? (Note that your code as written won't even compile, because you're neither catching `IOException` nor declaring that `main` can throw it.) – Jon Skeet Mar 02 '13 at 08:20
  • What is the message that you get with the exception? – Aurand Mar 02 '13 at 08:20
  • Ahh, I think the OP means that the compiler is objecting about an unhandled exception, not that an exception is actually being thrown. – Aurand Mar 02 '13 at 08:22

3 Answers3

3

Wrap it around try/catch block as File#createNewFile() might throw IOException in case of IOError.IOException is a checked exception and in java compiler will force you to handle/declare checked exceptions in the code yourself.

try {
File f= new File("Buns.dat");
f.createNewFile();
}
catch(IOException ex){
ex.printStacktrace();
}

From java 1.7 using try-with-resource Statement:

try(File f= new File("Buns.dat")) {
    f.createNewFile();
    }
    catch(IOException ex){
    ex.printStacktrace();
    }

If you choose to use try-with-resource statement, the only difference is that you don't need to closeyour resouces explicitly using finally block. To use try-with-resource though the object which you use inside the try-with-resource statement must implementjava.lang.AutoCloseable`.

You can also propagate the exception by using throws clause in your method signature.

public static void main(String[] args) throws IOException {

Related:

Community
  • 1
  • 1
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0
public static void main (String [] args) throws IOException
{
    File f= new File ("Buns.dat");
    f.createNewFile ();
}
Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
0

Check that you have permission to create a file in the directory you are running in.

SteveP
  • 18,840
  • 9
  • 47
  • 60