Solved

file.renameTo : linux v windows

Posted on 2004-08-01
9
726 Views
Last Modified: 2008-01-09
Can someone tell me why this works on Windows but not on Linux if renaming to a different partition :

import java.io.*;

public class moveFile {

public static void main(String[] args) {
File f = new File(args[0]);
System.out.println("Moving file "+args[0]+" to "+args[1]);
boolean ok = f.renameTo(new File(args[1]));
System.out.println("Move file was : "+ok);

}
}

running it on Linux with :

this works : java moveFile /opt/test1/testfile /opt/test2/testfile
this doesn't : java moveFile /opt/testfile /tmp/testfile

Thanks,

D.
0
Comment
Question by:damianharvey
  • 4
  • 3
  • 2
9 Comments
 
LVL 92

Expert Comment

by:objects
ID: 11690193
because renaming to a different partition is actually a copy and delete if across partitions.
0
 

Author Comment

by:damianharvey
ID: 11690559
So what stops this working? It isn't a permissions thing. I've chmod'ed all the dirs and files and run it as root.

What do most people do to get this functionality on Linux?
0
 
LVL 92

Expert Comment

by:objects
ID: 11690569
I don't think you can avoid doing a copy/delete.
what happens if you do a mv from command line?
0
ScreenConnect 6.0 Free Trial

Discover new time-saving features in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

 

Author Comment

by:damianharvey
ID: 11690676
mv from command prompt is fine. No issues.

It is specific only to java. I can move files using the Linux Tools (eg. Konqueror) with no issues as well.

Just found a couple of links on google that suggest that it isn't possible for Java to rename across Partitions/Devices. Seems odd that such functionality would be crippled on Linux.
0
 
LVL 92

Expert Comment

by:objects
ID: 11690721
from the javadoc:

"Whether or not this method can move a file from one filesystem to another is platform-dependent"
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 11691019
Since Windows 2000 the C-API supports renaming to be a move file.
So JAVA on Windows just tries an ordinary rename which is (sometimes!) carried out as a file move
on the OS-level. LINUX and UNIX don't.
The implementation of the rename operation is the cause of all this and not visible
from JAVA. The best you can do is write code that "copies & deletes" when a rename fails.
So I did.
;JOOP!
0
 
LVL 92

Accepted Solution

by:
objects earned 125 total points
ID: 11692003
A workaround would be to use Runtime.exec() to call mv
0
 

Author Comment

by:damianharvey
ID: 11722976
mv is the way to go I think. Here's the code I ended up using. I'm not sure why but the "-c" is required to get it working :

            if(!file.renameTo(archiveFile)) {
                        //Rename was not sucessful
                        if(File.separator.equals("/")) {
                              //You're on UNIX-LINUX-Solaris etc
                              try {
                                    
                                    String[] cmd = {"/bin/bash", "-c", "mv "+replaceSpaces(file.getAbsolutePath())+" "+replaceSpaces(archiveFile.getAbsolutePath())};
                                    log("Rename didn't work. Executing 'mv' command - "+cmd[0]+"; "+cmd[1]+"; "+cmd[2]);
                                    Process p = Runtime.getRuntime().exec(cmd);
                                    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                                    BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));

                                    String content = "";
                                    
                                    while((content = stdInput.readLine()) != null) {
                                          log("Command std output : "+content);
                                    }
                                    stdInput.close();
                                    
                                    while((content = stdErr.readLine()) != null) {
                                          log("Command err output : "+content);
                                    }
                                    stdErr.close();
                                                                  
                                    log("Moved the file successfully using mv");
                                    
                                    return true;
                                    
                              } catch(IOException e) {
                                    log("IOException using mv on *IX System :"+e);
                              }
                        }
            } else {
                log("Moved the file successfully using rename");
                return true;
            }
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 11723443
I found that it's faster (!?) and more controllable to copy a file yourself (don't ask me why/how).
So, I made a 'move' in JAVA because of system-independency:

     if(fileOld.renameTo(fileNew))
     {
            if(copy(fileOld, fileNew)) // true == OK
            {
                     fileOld.delete();
            }
     }

You can easily make your own copy show progress on the screen and copy filemode as well.
;JOOP!
0

Featured Post

ScreenConnect 6.0 Free Trial

Want empowering updates? You're in the right place! Discover new features in ScreenConnect 6.0, based on partner feedback, to keep you business operating smoothly and optimally (the way it should be). Explore all of the extras and enhancements for yourself!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Basic Java Case or If-Else statement... 3 50
javap not working 8 45
Custom Java Application connects to database: Which one of the 20? 4 28
printf performancy 11 42
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

777 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