user5118384
user5118384

Reputation:

Rename file from outside when it's opened in Java

I'm coding a Java Application right now and it has to read through a file. I'm using this method to do so:

BufferedReader mb_reader = new BufferedReader(new FileReader(f1));
int lines = 0;
while (null != (mb_line = mb_reader.readLine())) {
    lines++;
    //something to do
}

Everything works fine but it's possible that the file has to be changed from outside (for example).

I have a mthod that tests if the file exists and then open this reader. But if I now try to rename the file in the Windows Explorer it just says that the file is opened in Java and can not be renamed.

Is there a way to make it possible to rename it even if it's opened?

Upvotes: 4

Views: 385

Answers (3)

das Keks
das Keks

Reputation: 3941

If only the file name has to be changed while reading but the content stays the same, I would create a temporary copy of that file and read from that copy.

This way you wouldn't lock the original file and still can access the content.

Upvotes: 0

Laurentiu L.
Laurentiu L.

Reputation: 6686

You need to close the stream to release the file to the system, i don't think there's a straightforward way around this.

You could have a working copy to read from and check the file every now and then for changes you might expect.

Upvotes: 1

breakline
breakline

Reputation: 6073

Maybe you should read the file first totally into a StringBuilder or similar if its not too large then release it so the other thread or process can access it. I mean reading the file can be pretty fast compared to holding it open while you process it completely.

Upvotes: 0

Related Questions