Does RandomAccessFile create a new file, if the specidied one does not exist? Does it replace the file with a new one if it does exist?

I’ve already created a method that uses createNewFile to create a new file and it does so successfully. I’ve also made a method that’s supposed to open files, using randomAccessFile. Due to some issues I checked to see whether a new file is created if I put a new name as a parameter in randomAccessfile and it is. I was wondering if that’s actually the case and if so, what can I replace it with in order to open files and read-write on them. I can’t change much to the “general idea” of my program since this is a part of an assignment.


The documentation of the RandomAccessFile states about the mode parameter to the class’s two constructors:

“r” Open for reading only. Invoking any of the write methods of the
resulting object will cause an IOException to be thrown.

“rw” Open for reading and writing. If the file does not already exist then an
attempt will be made to create it.

The file is only created or modified if you supply a “w” in to the file mode. The file will be created if it doesn’t exist, but the contents will not be changed if the file does exist because you are opening the file for both reading and writing.

There is no write mode that causes a file to be opened only if it exists, failing otherwise. To get that functionality in your code, you’d want to first check for the existence of the file, and have your logic do whatever is appropriate when the file does not exist.

Source: stackoverflow