• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Junilu Lacar
  • Martin Vashko
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Scott Selikoff
  • salvin francis
  • Piet Souris

How to rename a file in JAVA ?

 
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey All,

I have a file that i process for some business data.

Once i process the data, i need to rename the file and place it in a specific directory ( i create the directory during the process).

I create a new directory ( if it does not exist) and also create a new temp file (empty file) File.createTempFile(fileName, fileFormat, dir) .

Now, i am trying to rename the existing file to this new destination.

somehow, this operation always fails and a value of false is returned.

Any help wil be appreciated

 
Ranch Hand
Posts: 2410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you released any FileReader associated with the file?
 
Vicky Mohan
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FileInputStream input = new FileInputStream("file");
BufferedReader fileReader = new BufferedReader(new InputStreamReader(input));

///// PROCESSING /////////


File destFile = new File("newfilePath");
boolean flag = file.renameTo(destFile);

DO you mean to say that i need to close the fileReader ??
 
author and iconoclast
Posts: 24203
43
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Raj Verma:

DO you mean to say that i need to close the fileReader ??



On Windows, yes, indeed.

Note, also, that renameTo() will work only within a single filesystem (disk). To "rename" a file across disks, you need to copy the contents and delete the old file. It's a good idea to try renameTo(), then do copy/delete as a backup.
 
rubbery bacon. rubbery tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!