File.renameTo

Hi,
Does file.renameTo work on AIX Server,and how much time will this method take to move a file of 35 million records?
Regards
KK

NAME
rename - rename a file
SYNOPSIS
   #include <stdio.h>
    int rename(const char old, const char new);
DESCRIPTION
The rename() function changes the name of a file.
The old argument points to the pathname of the file to be renamed.
The new argument points to the new pathname of the file.
posman@proli:~/ivan> df -k . /tmp
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/cciss/c0d0p3     16682556  14755300   1927256  89% /home
/dev/cciss/c0d1p2     35539772  33619432   1920340  95% /
posman@proli:~/ivan> cat x.c
#include <stdio.h>
int main() {
int r =  rename("movethis","/tmp");
if (r !=0) perror("rename");
return r;
}posman@proli:~/ivan> gcc x.c -o x
posman@proli:~/ivan> ./x
rename: Invalid cross-device link
Edited by: BIJ001 on Oct 1, 2007 9:01 AM

Similar Messages

  • Concurrent processing & file.renameTo(...)

    Hi,
    I've can successfully move a file in the single thread/process environment using file.renameTo
    However in the multithreaded/multiple process environment, the initial file is several MB (about 100mb). It is created on the fly outside of my thread and takes several minutes to build.
    I would like to rename it after the file is finished building.
    In my code I do the following:
    boolean success = false;
    while (! success)
    success = inputFile.renameTo(dest);
    QuickSleep(1500); // Performs a Thread.sleep in a try/catch
    I've seen some weird behavior however. On a windows box the renameTo seems to return false if the other process is still writing to the file. However on linux the .renameTo is returning true even though the file hasn't finished building.
    The end result on linux is I end up with two files. One that got renamed and is partially filled and the other original with the rest of the file.
    Is there a way to know when the file isn't being written by another process/thread?
    Thanks in advance.

    if by now you still have the problem (FYI this is working on AIX) have a look at my solution:
    for (int i = 0; i < dir.listFiles().length; i++) {
    try {
         Process p = Runtime.getRuntime().exec("/usr/sbin/fuser " + dir.listFiles().getAbsolutePath());
         p.waitFor();                              
         InputStream in = p.getInputStream(); // we have to read the stream to verify if there is a process id
         int c = in.read();
         String stream = "";
         while (c != -1) {
              stream = stream + (char)c;
              c = in.read();
         if (stream.trim().length() > 0) {
              logger.info("File: " + dir.listFiles()[i] + " is in use by process ID:" + stream);
              try {
                   Thread.sleep(5000); //sleep for 5 sec
              } catch (InterruptedException e){
                   // the VM doesn't want us to sleep anymore,
                   // so get back to work
              continue;
    } catch (Exception e) {
         logger.error("fuser exception: " + e.getMessage());

  • Java.io.File renameTo does not work on Solaris

    Hi Experts,
    I have a code-piece which tries to move files from one directory to another on the SAME FILE SYSTEM using java.io.File.renameTo method.
    It works fine when there less no. of files in the source directory. But the renameTo does not work as expected when there are very huge no. of files(~40K) present in the source directory.
    I am aware that there is a known issue when one tries to use this method to move files across file systems OR if the file exists at the destination directory.
    But in my case the file system is the same and the there is no such file in the destination directory.
    I suspect some inode related issues. But not sure what it is exactly.
    Is there any limitations of renameTo?
    Please help.

    OK, we all now understand you have a problem in doing this, but without the specifics of the problem that you are experiencing, then it is fairly difficult to give you anything other than a guess. If you would like some specific and relevent answers, please supply specifics about how exactly the operation differs from your expected results. You should also post example code as it is almost always asked for eventually.

  • File.renameTo(File) doesn't change dirs on Linux?!

    Hi All,
    I'm trying to change a file's name and directory with File.renameTo but it doesn't work. It says in the manual that changing dirs is O/S dependent, so i guess it doesn't work on Linux.
    Is it correct? if so, what can be done to change a file's name and directory?
    File oldFile = new File(filePath);
    oldFile.delete();   // Delete old file
    File newFile = new File(newFilePath);     // This is the new file
    File tempFile = new File(filePath);          // Get name to renameTo
    newFile.renameTo(tempFile)                  // Try to rename

    Hmm, it worked for me, though I didn't try deleting the oldFile. A simple move from one directory to another was not problem, though. The rename would fail if the delete failed. You might check that.

  • File.renameTo() and locking

    Hi,
    I would like to rename file, but File.renameTo() will not work if the file will be locked by some other process. If other process has locked the file, I would like to wait for it to release the lock. So I have:
    FileLock lock = new RandomAccessFile(file, "rw").getChannel().lock(0L, Long.MAX_VALUE, false);
    file.renameTo(destFile);
    lock.release();But this does not work, because file is locked and renameTo does not work (returns false).
    What can I do to lock the file myself (wait for other locks to be released) and to rename it (rename does not work when file is locked).
    Regards
    Pawel Stawicki

    hi, I don't thik you have to lock the file yourself while renaming it because that is (from my point of view) an opperating system's job to do it.
    you could maybe make a
    while(! file.renameTo()){
    thread.sleep(1000);
    to wait till its unlocked.
    I'm not sure that helps but that's just an idea

  • File.renameTo() bugg? Leaves the file open

    I came across the strangest behaviour of File.renameTo() for the following steps:
    1. Rename a file - successful
    2. Rename the same file again - will fail. Also delete will fail.
    -------- some code ----------
    File file=new File("F1");//nonexistent file
    //write some to the file - just to make the file to be created
    RandomAccessFile rFile=new RandomAccessFile(file,"rw");
    rFile.writeBytes("Hello");
    rFile.close();
    //A successful rename
    boolean renamed=file.renameTo(new File("F2"));
    System.out.println("renamed="+renamed);
    //This is commented code for now
    //rFile=new RandomAccessFile(file,"rw");
    //rFile.close();
    //This rename fails!
    renamed=file.renameTo(new File("F3"));
    System.out.println("renamed again="+renamed);
    As it seems File.renameTo() sets the file to open, since neither renameTo or delete will work after a renameTo.
    BUT, if I uncomment the commented code, it will work again! I just open a dummy RandomAccessFile (FileInputStream would work as well I guess) and then close it, and somehow the file is set to closed again, and the second renameTo() will work.
    Is this a bugg in File.renameTo()? I run on windows XP and have java 1.4.1_02-b06. I couldn't find any comment about this in the Bug Database.
    Gil

    Aha! so the reason why the opening of the dummy RandomAccessFile did it in my previous code, was becase it created the old File "F1" again that could be renamed again. So the correct code should instead be:
    -------- some code ----------
    File file=new File("F1");//nonexistent file
    //write some to the file - just to make the file to be created
    RandomAccessFile rFile=new RandomAccessFile(file,"rw");
    rFile.writeBytes("Hello");
    rFile.close();
    //A successful rename
    File file2=new File("F2");
    boolean renamed=file.renameTo(file2);
    System.out.println("renamed="+renamed);
    //Now this rename also succeeds!
    renamed=file2.renameTo(new File("F3"));//do rename on file2!
    System.out.println("renamed again="+renamed);
    Gil

  • File.renameTo method issue

    I have a Java program which processes upto 10000 text files a day. The average size of these files are 1KB to 2KB and the java program parses the contents of the text file, validates and loads them into a database table.
    The program outline is as follows
    File[] filesToProcess = sourceFolder.listFiles();
    int fileCount = filesToProcess.length;
    for (int i=0;i<fileCount;i++) {
    File currentFile = filesToProcess;
    MsgParser fileParser = new MsgParser(currentFile);
    if ( fileParser.isMessageValid()) {
    boolean uploadSuccess = fileParser.uploadToDB();
    if (uploadSuccess) {
    if (currentFile.renameTo(parseSuccessArchiveFile))
    logger.info("File successfully moved to archive folder);
    else
    logger.info("File cannot be moved to archive folder);
    } else {
    if (currentFile.renameTo(parseFailureArchiveFile)
    logger.info("Parser failed file moved to archive folder);
    else
    logger.info("Parser failed file cannot be moved to archive folder);
    The above program outline works well. However the renameTo method is not renaming the parsed files successfully on all occasions. There is no performance issue involved here as the files keep streaming in throughout the day and the program is able to handle the parsing of the file(s) in a fraction of second.
    The issue for me is that I keep picking the files to parse from the source folder at regular intervals ( after a full iteration of the files list, wait for 10 seconds before calling for a new set of files ) and cannot afford to have a failure in moving the file to the archive folder as otherwise, I end up parsing the same file multiple number of times, which I want to avoid.
    Can anyone shed some light on the behavior of File.renameTo and how to make it work successfully?
    Sundar

    I am making the code more readable for you all and corrected some typo errors...
    File[] filesToProcess = sourceFolder.listFiles();
    int fileCount = filesToProcess.length;
    for (int i=0;i<fileCount;i++) {
          File currentFile = filesToProcess;
          MsgParser fileParser = new MsgParser(currentFile);
          boolean uploadSuccess = false;
          if ( fileParser.isMessageValid())
               uploadSuccess = fileParser.uploadToDB();
          if (uploadSuccess) {
                if (currentFile.renameTo(parseSuccessArchiveFile))
                      logger.info("File successfully moved to archive folder);
                else
                      logger.info("File cannot be moved to archive folder);
          } else {
                if (currentFile.renameTo(parseFailureArchiveFile)
                      logger.info("Parser failed file moved to archive folder);
                else
                      logger.
                      info("Parser failed file cannot be moved to archive folder);
    }

  • JFileChooser and File.renameTo()

    Hi,
    Anyone experienced strange behaviour from the JFileChooser returned
    File Object. In my case it's an instance of:
    sun.awt.shell.Win32ShellFolder2
    Unfortunatly the File.renameTo(File file) method doesn't work
    properly with this File instance.
    Anyhelp is welcome / dzone

    overwrite the approveSelection() method of your JFileChooser. in there you can do your checks before executing super.approveSelection().
    tthomas

  • File.renameTo(..) does not work with NFS?

    I have some code the essentially does this:
    1. Create Destination Directories
    file.mkdirs(..);
    2. For each file..'rename to destination'
    for (..)
    file.renameTo(..);
    * Where the rename To is 'moving' the file to the dest directory.
    This code works fine on LocalDrive to LocalDrive.
    But when I goes to the NFS...
    The Directories get created on the NFS.
    But the files never make it there..no exception is thrown...
    Has Anyone encountered such behavior before?
    The system obviosly has write permissions since the directories do get created...

    ok...something that has been bugging me..
    We all know that Java IO is dog slow (perhaps now with 1.4 it is better with non blocking io)..but..here's my gripes..
    for Java API calls where a native equivalent exists on the OS, then native equivalent should be invoked (as it is more then likey going to be faster). In other words shouldnt renameTo call mv on unix.
    now java has no copy method..so..some time ago..I implemented a 'native' copy..simply system.exec("cp ") etc..(much quick the copying the streams)
    This works..but after finding out the system.exec FORKS the entire VM, we can no longer use this, as memory requirements are strict.
    It seams to me that sun has messed up here...
    or am I missing something?
    thoughts?
    Dan

  • Can't rename a file using File.renameTo(...)

    Hi,
    I have a servlet, RenameFile, that receives audio file via HTTP Post and writes it to /tmp/recording.0002002B-0C0022BB-0001.1.20050622.073208.wav. Then it creates directories under /alert_messages directory based on the timing parameters that it get. Finally, it renames /tmp/recording.0002002B-0C0022BB-0001.1.20050622.073208.wav to /alert_messages/2005/06/22/22/00/79_0_200506222200_001.WAV. RenameFile runs fine when it runs by itself (ONLY one Tomcat, jakarta-tomcat-4.1.30, is running). However, RenameFile fails to rename the /tmp/recording.0002002B-0C0022BB-0001.1.20050622.073208.wav to /alert_messages/2005/06/22/22/00/79_0_200506222200_001.WAV when it runs in a Linux box that jboss-3.2.1_tomcat-4.1.24 is also running. In this box, TWO versions of Tomcat are running at the same time. I set the /alert_messages directory with �chmod �R 777� and run jakarta-tomcat-4.1.30 as tomcat user. RenameFile fails the rename operation. But, it creates the /alert_messages/2005/06/22/22/00/ directories.
    It seem like RenameFile can create directory but can�t create file in the /alert_messages directory when both version of tomcats are running at the same time.
    Can it be due to both the jakarta-tomcat-4.1.30 and the jboss-3.2.1_tomcat-4.1.24 versions are running at the same time in one Linux box?
    Can this be Jboss prevented the operation?
    I did not receive any io exception!!!
    Any help in this issue is greatly appreciated.
    Debug listing from the RenameFile;
    - originalFilename: recording.0002002B-0C0022BB-0001.1.20050622.073208.wav
    - file.toString(): /tmp/recording.0002002B-0C0022BB-0001.1.20050622.073208.wav
    - file.getName(): recording.0002002B-0C0022BB-0001.1.20050622.073208.wav
    - file.length(): 122986
    - file /alert_messages/2005/06/22/22/00/79_0_200506222200_001.WAV
    - file NOT renamed /alert_messages/2005/06/22/22/00/79_0_200506222200_001.WAV
    File Listing in the /tmp directory create by RenameFile;
    -rw-r--r-- 1 tomcat tomcat 122986 Jun 22 07:33 recording.0002002B-0C0022BB-0001.1.20050622.073208.wav
    Directoy Listing in the / directory with �ls �la�;
    drwxrwxrwx 3 tomcat tomcat 4096 Jun 22 07:28 alert_messages
    Directory created by the RenameFile with �ls -la /alert_messages/2005/06/22/22/00�;
    drwxr-xr-x 2 tomcat tomcat 4096 Jun 22 07:33 .
    drwxr-xr-x 3 tomcat tomcat 4096 Jun 22 07:33 ..
    Out put from catalina.out;
    !!!!! Can Read the old File !!!!!!!!!!!!!!!!!!!!
    !!!!! Can Write the old File !!!!!!!!!!!!!!!!!!!!
    !!!!! Can Not Read the new File !!!!!!!!!!!!!!!!!!!!
    !!!!! Can Not Write the new File !!!!!!!!!!!!!!!!!!!!
    !!!!! renameTo return false !!!!!!!!!!!!!!!!!!!!
    Code That rename a file:
      public synchronized String renameAlertMessageFile(String oldFileName,
                                String newFileName)
                throws SecurityException, NullPointerException
        File oldFile = null;
        File newFile = null;
        String result = null;
        StringBuffer myNewFileName = null;
        boolean renamed = false;
        try {
          int indexStringValue;
          int newFileLength;
          int indexOfPeriod;
          int indexOfLastUnderScore;
          int lengthOfExtension;
          boolean  Contin = true;
          String sNumber = null;
          String indexString = null;
          myNewFileName = new StringBuffer(newFileName);
          oldFile = new File(oldFileName);
          newFile = new File(myNewFileName.toString());
          if (oldFile.canRead() == false) {
            System.out.println(" !!!!!  Can Not Read the old File !!!!!!!!!!!!!!!!!!!!");
          } else {
            System.out.println(" !!!!!  Can Read the old File !!!!!!!!!!!!!!!!!!!!");
          if (oldFile.canWrite() == false) {
            System.out.println(" !!!!!  Can Not Write the old File !!!!!!!!!!!!!!!!!!!!");
          } else {
            System.out.println(" !!!!!  Can Write the old File !!!!!!!!!!!!!!!!!!!!");
          if (newFile.canRead() == false) {
            System.out.println(" !!!!!  Can Not Read the new File !!!!!!!!!!!!!!!!!!!!");
          } else {
            System.out.println(" !!!!!  Can Read the new File !!!!!!!!!!!!!!!!!!!!");
          if (newFile.canWrite() == false) {
            System.out.println(" !!!!!  Can Not Write the new File !!!!!!!!!!!!!!!!!!!!");
          } else {
            System.out.println(" !!!!!  Can Write the new File !!!!!!!!!!!!!!!!!!!!");
          renamed = oldFile.renameTo(newFile);
          if (renamed == false) {
            System.out.println(" !!!!!  renameTo return false !!!!!!!!!!!!!!!!!!!!");
        } catch (NullPointerException ex) {
          // Throw the same exception so that the caller may catch the
          //   exception and log the error
          System.out.println("NullPointerException For The New Dest File Name");
          ex.printStackTrace();
          throw ex;
        } catch (SecurityException seEx) {
          System.out.println("SecurityException For The New Dest File Name");
          seEx.printStackTrace();
          // Throw the same exception so that the caller may catch the
          //   exception and log the error
          throw seEx;
        } finally {
          if (renamed == true)
            return myNewFileName.toString();
          else
            return null;
      } // End renameAlertMessageFile

    Hi,
    Thank you for replying to my message. The servlet has been running for me for the last 12 months. However, it was running by itself without the Jboss-tomcat running on the same box. Can this be the catalina.policy file in the jboss-tomcat version restricted the rename operation. We are not allowed to write file under the umbrella of J2EE. But the servlet did not run within Jboss-tomcat. This really gets me thinking that something is not working correctly. Perhaps tomcat did not has the permission to write on the /alert_messages directory, again it did created the subdirectories under the /alert_messages.
    Any idea of what is going on?

  • Why is File.renameTo(...) so instable?

    Hello,
    I got an average success ratio of 5:1 under WinXP. Looking into the sources didn't help me any further.
    I saw in the ANT-code that there a COPY operation is immediately launched as a workaround if the renameTo(...) fails. But it's such a basic operation after all. Any experiences?

    Thank you all.
    I think the code I used is quite ordinary (in- and outfile are in the same directory):
        String filspc, zeile;
        try {
          File f= new File(filspc);
          File fTmp= new File(filspc+".tmp");
          BufferedReader infile = new BufferedReader(new FileReader(f));
          BufferedWriter outfile= new BufferedWriter(new FileWriter(fTmp));
          while ((zeile= infile.readLine()) != null) {
         outfile.write(zeile, 0, zeile.length());
         outfile.newLine();
          infile.close();
          outfile.close();
          File fBak= new File(filspc+".bak");
          System.out.println(f.renameTo(fBak));
          System.out.println(fTmp.renameTo(f));So the possibility of a lock seems to me the most likely.
    However, I also made a loop in case of failure and tried to rename again after a few seconds - but to no avail. A file lock would have had time enough to be released.
    And don't forget: in five cases out of six renameTo() worked straight away without any problem.

  • File.renameTo() Question

    I am writing a small utility to parse some files and all is well except when there is a colon in the "to" filename i.e.
    fileName = "MONDAY : 9AM.TXT"
    It doesn't like the colon. Any way around this???
    The files that don't have colons work fine but, any new filename that contains a colon will return false (from renameTo())
    Thanks,
    Kevin

    fileName = "MONDAY : 9AM.TXT"Did you ever tried to save the file with the above format.....i guess windows doesn't allow this format

  • File.renameTo(File dest)

    I have to rename the file.
    File f1 is the existing file
    I created the instance of the file
    File f2 = new File(file name with path)
    now iam trying to rename f1 to f2,I used f1.renameTo(f2)
    It's working fine on w2k but failing in UNIX.
    when I check canWrite() on f2, Iam getting false on UNIX.
    Please tell me the way to getaround, I don't want to set the permission.

    Either your file name is specified incorrectly for the UNIX platform, simply does not exist, or you don't have permissions to rename it.

  • File.renameTo, explain this...

    Hi.
    This peace of code:
    File f = new File("C:/before.txt");
    System.out.println( f.getName() );
    f.renameTo( new File("C:/after.txt") );
    System.out.println( f.getName() );
    output is:
    before.txt
    before.txt
    and my filesystem has properly changed the name
    from before.txt to after.txt
    If the name change went ok, shouldn't the second print be "after.txt" ?
    regards
    Andreas

    Probably not as f.getName() refers to File f.
    While the File f has been successfully renamed, this does'nt affect the instance of File you are checking. Get it?
    This might help make it more clear:
    import java.io.*;
    public class Rename {
        public static void main(String [] args) {
            File before = new File("./", "before.txt");
            File after = new File("./", "after.txt");
            System.out.println(before.getName() + " was renamed? " + before.renameTo(after));
            System.out.println(after.getName());
    }roy% ls
    Rename.class Rename.java before.txt
    roy% java Rename
    before.txt was renamed? true
    after.txt
    roy% ls
    Rename.class Rename.java after.txt

  • Java.io.File.renameTo

    Is there any limitation on renameTo(file) method. It fails when I try to rename a file from root user to a different file which belongs
    to a different user. I'm running the code as root. Root should have permission to write anywhere.
    Also, I'm trying to rename the file within the same physical device.

    I have gone thru javadoc, but it does not provide the necessary answer. I don't get any error message or exception.
    I'm using RHEL 5.2 and jdk 1.5.

Maybe you are looking for

  • SP to check PO max qty

    Hi, I'd like to create SP to check maximum quantity in PO and current on hand compare with maximum stock in warehouse.  I have created a query, but unfortunately it's not working well. Here's the query: IF @transaction_type IN ('A','U') AND @object_t

  • Oracle Sqldeveloper

    I am using oracle sqldeveloper 1.0.0.15.57. Previously we were able to set up a breakpoint and step through a stored procedure inside a package. We made sure all the previliges are on and the debugging did really work. But after some time (no changes

  • Set currency value of pricing element in condition tab - VA21

    Hi GURU, Would you please help to identify the way to set the following currency values for pricing element in condition tab when creating system quote by va21: Rate unit (RV61A-KOEIN) SD document currency (KOMK - WAERK) Thanks in advanced, Regards,

  • Parent.frame.location problem in firefox

    Hello! I'm making a JSP page which opens a new page with 2 frames. The left frame has links which changes the location of the right frame. The right frame either displays an oracle report or another JSP that displays a PDF file. The thing is, I use p

  • Converting Demo Movie to Custom or Training simulation

    Does anyone know if there is a way to convert an exiting movie into a trining or custom simulation where the user would actually have to do the mouse clicks and enter the information for training?