Solved

renaming an existing file

Posted on 1997-10-31
2
508 Views
Last Modified: 2010-05-18
How do you rename an existing file on a local drive? In my application, I save a new file to a temporary name, and then rename it to the real name after I finish writing data to disk. In the method doSave(), I pass a File object that I create based on information the user specifies in a FileDialog. Note that theFile doesn't exist yet, it simply describes the file's pathname:



private boolean doSave(File theFile)

{

// create a unique file name for the temp file

String tempName = "_" + String.valueOf(System.currentTimeMillis());

File tempFile = new File(theFile.getParent(), tempName);



// create a RandomAccessFile object and pass to application's method

RandomAccessFile aRaf = new RandomAccessFile(tempFile, "rw");

myApp.writeData(aRaf);

// data is safely written to hard disk, so now rename temp file to real file name I want

boolean savedOK = (tempFile.renameTo(theFile));

return savedOK;

}



The method always returns false. The data is written to disk correctly, but the call to renameTo never works, and the file still has the temporary name.
0
Comment
Question by:dacton
2 Comments
 
LVL 4

Accepted Solution

by:
russgold earned 200 total points
Comment Utility
You cannot rename a file while it is open.  

Add the line:

aRAF. close();

before:

tempFile. rename( theFile );
0
 

Author Comment

by:dacton
Comment Utility
Yikes! I should have figured that one out. I added the close() call it it all works now. Thanks for the quick response.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now