Solved

renaming an existing file

Posted on 1997-10-31
2
514 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
ID: 1229705
You cannot rename a file while it is open.  

Add the line:

aRAF. close();

before:

tempFile. rename( theFile );
0
 

Author Comment

by:dacton
ID: 1229706
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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

776 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