简体   繁体   中英

Java: Is it possible to open a file for writing, but blow up if the file already exists?

I want to create a file for writing and get an exception if the file with the given name already exists. I'm looking for an implementation that is thread-safe, and hopefully in the Java standard library. The closest call I have found is this:

FileOutputStream fos = new FileOutputStream("/some/file/path.txt");

But this will truncate an existing file with the same name. Is there any method that will throw an exception or otherwise return an error, if there is a file with the same name already?

Try using File class and createNewFile .

Following solution is thread safe:

File file = new File("/some/file/path.txt");
if (file.createNewFile()) {
  // Succesfully created a new file
  FileOutputStream fos = new FileOutputStream(file);
  try {
    // Do something with outputstream
  } finally {
    try { fos.close(); } catch (IOException exception) { }
  }
}

This is the method you want: File.createNewFile

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist . The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.

You can

  • check the file exists
  • if it doesn't write to a temporary
  • rename the temporary file to the original
  • delete the temporary file if it fails to rename.

As the third step is atomic in the OS so its thread and process safe.

File f = new File("/some/file/path.txt");
if(f.exists()) 
  {
   //delete the file
  }
   else
  {
    //create and do what you want
  }

Yes there is another way and it also integrates easily with your code:

synchronized(this) {
  File f = new File("path");

  if (f.exists())
    throw new FileExistsException();
  else {
    FileOutputStream fos = new FileOutputStream(f);
    ...
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM