Would Java be able to .rename() a file while it is still being written, or will it detect that the file is in use?

Also, is it possible to open a file for exclusive access in Java, and will this fail if the file is still being written?

Thanks.

You can definitely rename a file in Java, use this:

public class Rename {
  public static void main(String[] argv) throws IOException {

    // Construct the file object. Does NOT create a file on disk!
    File f = new File("Rename.java~"); // backup of this source file.

    // Rename the backup file to "junk.dat"
    // Renaming requires a File object for the target.
    f.renameTo(new File("junk.dat"));
  }
}

I am assuming that one could do that during runtime, while it is being written to, but make sure they are not on seperate threads or if they are, lock the thread before trying because I am not 100% sure.

What do you mean open a file exclusively for Java?

I think the question is "can one open a file for exclusive access - ie, get an flock - in a java program". Not "can one open a file, for exclusive access by Java" (ie, open a file so only Java can use it).

Don't know the answer off the top of my head, if it comes to me I'll post it, but I think that's the right question.

Edited 6 Years Ago by jon.kiparsky: n/a

You're perfectly right, I asked the question wrong.

The answer is yes, you can open a file for exclusive access - I just found that out.

What I'm not sure of now is this; will trying to get exclusive access cause whatever is writing the file to be locked out, and the writing stopped, or will the attempt to get exclusive access fail if the file is still being written?

Oh, I am actually very sure that if the JVM is accusing a file, that the OS itself will return an error to any other program requesting access, simply because if you try and edit a file while another person is using it, it will give an error, but ya I do not know off the top of my head :)

Thx a lot, you've been really helpful ^^

Marking this as solved.

This question has already been answered. Start a new discussion instead.