• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with renaming file after reading it

 
Mats Villen
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a problem with renaming a file after reading it.

first I open the file

File f = new File(s);
br = new BufferedReader(
new InputStreamReader(
new FileInputStream(f)));

I read the file
String line = readFile(br);

The file is closed
br.close();

Then I try to rename the file
File a = new File(s);
a.renameTo(new File(s+".done"));

But the file is not renamed and seems to be locked by the progam. If a close the program and start again and the file can be renamed.
Should the file be closed in a different way?

thanks in advance
Mats
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The most common cause for this sort of problem is failure to close the stream. So, are you absolutely sure that the stream was closed? What if an exception was thrown during the file reading - would you see it? Would the stream get closed regardless? (This is a good use for a "finally" block.)

Also - are you sure there aren't any other streams using the file? Reading or writing? If there are, make sure they're closed as well.

If you've checked this and are sure everything is closed, I don't know. There may be a defect in the filesystem - or in the Java implementation of file I/O activities. Depending on your perspective. Try inserting a short pause (e.g. with Thread.sleep()) in the program before you try to rename - does it make a difference?
 
Ronald Djunaedi
Greenhorn
Posts: 5
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike Simmons wrote:The most common cause for this sort of problem is failure to close the stream. So, are you absolutely sure that the stream was closed? What if an exception was thrown during the file reading - would you see it? Would the stream get closed regardless? (This is a good use for a "finally" block.)

Also - are you sure there aren't any other streams using the file? Reading or writing? If there are, make sure they're closed as well.

If you've checked this and are sure everything is closed, I don't know. There may be a defect in the filesystem - or in the Java implementation of file I/O activities. Depending on your perspective. Try inserting a short pause (e.g. with Thread.sleep()) in the program before you try to rename - does it make a difference?


Im quite agree with Mike, make sure to put all closing event in the finally block, to make sure they will be executed...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!