Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming a file without using renameTo() - Java

Disregarding my last post, I've found the source of the problem. I'm using

a.renameTo(b)

when b doesn't exist. The reason it doesn't exist is because there is a symbolic link so if b is /usr/name/folder/file, then b really is /mnt/MountTest because the symlink is to that directory.

So the question is, is there an alternative way to rename a file in Java using a string value? If not, how can this rename procedure be done differently?

like image 429
Hristo Avatar asked Jan 06 '10 16:01

Hristo


People also ask

Which method is used to rename the file in Java?

In Java we can rename a file using renameTo(newName) method that belongs to the File class. Parameters: dest – The new abstract pathname for the existing abstract pathname.

How do you rename and move a file in Java?

To rename or move a file/directory in Java, you can use either the renameTo() method of a File object in the old File I/O API, or the Files. move() method in the new Java NIO API.


2 Answers

A rename would rename it... if it were on the same filesystem.

If a renameTo() fails, you'll need to copy it to the new location, then delete the original.

like image 59
Dean J Avatar answered Nov 01 '22 12:11

Dean J


Renaming files is also highly problematic accross file systems. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4073756. Commenters of the bug report posted some sample code and also pointed out that you can use Process.exec. Both Apache Commons IO and and Google Guava have utilities for safely moving files as well:

  • http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#move(java.io.File,%20java.io.File)
  • https://commons.apache.org/proper/commons-io/javadocs/api-1.4/org/apache/commons/io/FileUtils.html#moveFile(java.io.File,%20java.io.File)
like image 41
big lep Avatar answered Nov 01 '22 13:11

big lep