dublintech
dublintech

Reputation: 17785

Create a File if it is not already there

In Java we can create a reference to a file by...

File counterFile = new File("countervalue.txt");

but how do we create the file if it does not already exist?

Upvotes: 1

Views: 129

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

The basic way to create the file would be calling the File#createNewFile method:

File counterFile = new File("countervalue.txt");
try {
    counterFile.createNewFile();
} catch (Exception e) {
    System.out.println("File couldn't been created.");
}

Now, if you want to create a new File and fill it with data, you can use a FileWriter and a PrintWriter for text files (assuming this for the txt extension in your sample):

File counterFile = new File("countervalue.txt");
PrintWriter pw = null;
try {
    //it will automatically create the file
    pw = new PrintWriter(new FileWriter(counterFile));
    pw.println("Hello world!");
} catch (Exception e) {
    System.out.println("File couldn't been created.");
} finally {
    if (pw != null) {
        pw.flush();
        pw.close();
    }
}

If you want to just append data to your file, use the FileWriter(File, boolean) constructor passing true as the second parameter:

pw = new PrintWriter(new FileWriter(counterFile, true));

Upvotes: 2

David
David

Reputation: 375

Easily done in java

File counterFile = new File("countervalue.txt");
counterFile.createNewFile();

Upvotes: 1

Related Questions