Terence Lyu
Terence Lyu

Reputation: 329

Java create a new file, or, override the existing file

What I want to achieve is to create a file regardless of whether the file exists or not.

I tried using File.createNewFile() but that will only create the file if it does not already exists. Should I use File.delete() and then File.createNewFile()?

Or is there a clearer way of doing it?

Upvotes: 19

Views: 39515

Answers (4)

Volodya Lombrozo
Volodya Lombrozo

Reputation: 3454

Java 7 introduced the java.nio.file package which includes the very useful Files class. This class provides the write method that does precisely what you're looking for. To save a file or overwrite an existing one, you can use the following command:

Files.write(file, bytes);

Please note that the variable path here is of type Path. If you're using an instance of the File class, you may need to convert it to a Path using:

Files.write(file.toPath(), bytes);

You can read more about this method here:

In other words, it opens the file for writing, creating the file if it doesn't exist

Here's a test that demonstrates the method works as expected:

@Test
void createsOrOverwrites(@TempDir final Path temp) throws IOException {
    final Path text = temp.resolve("hello.txt");
    Files.write(
        text,
        "Hello, world!".getBytes(StandardCharsets.UTF_8)
    );
    Assertions.assertTrue(Files.exists(text), "File should be created");
    Assertions.assertEquals(
        "Hello, world!",
        Files.readAllLines(text).get(0),
        "File should contain correct text"
    );
    Files.write(
        text,
        "I love StackOverflow!".getBytes(StandardCharsets.UTF_8)
    );
    Assertions.assertEquals(
        "I love StackOverflow!",
        Files.readAllLines(text).get(0),
        "File should be overwritten"
    );
}

Upvotes: 1

Mureinik
Mureinik

Reputation: 310983

Calling File#createNewFile is safe, assuming the path is valid and you have write permissions on it. If a file already exists with that name, it will just return false:

File f = new File("myfile.txt");
if (f.createNewFile()) {
    // If there wasn't a file there beforehand, there is one now.
} else {
   // If there was, no harm, no foul
}

// And now you can use it.

Upvotes: 0

S.K.
S.K.

Reputation: 3677

You can use a suitable Writer:

BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt")));
br.write("some text");

It will create a file abc.txt if it doesn't exist. If it does, it will overwrite the file.

You can also open the file in append mode by using another constructor of FileWriter:

BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt"), true));
br.write("some text");

The documentation for above constructor says:

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Upvotes: 5

Bruno Caceiro
Bruno Caceiro

Reputation: 7179

FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:

Writer fileWriter = new FileWriter("c:\\data\\output.txt", true);  //appends to file

Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file

Upvotes: 19

Related Questions