Solved

Rename file in Java

Posted on 2014-11-19
6
413 Views
Last Modified: 2014-11-20
Hi,
I am renaming a file in Java on Linux O/S. The function renameTo returns true but file does not get renamed half the time. The file resides on a mounted folder on Linux machine. The code is below:

        // Rename the file with an appended .LOAD extension, so that next time
    // this program will not pickup the same file again
      String renameToFile = filename + ".load";             //filename is valid file name
      File sourceFile = new File(filename);
    if (sourceFile.renameTo(new File(renameToFile)))
    {
     //success, verify now
      File destFile = new File(renameToFile);
      boolean renamed = false;
      while (TIMES_TO_RENAME_VERIFY-- > 0)             //5 times
      {
        try
        {
          Thread.sleep(RETRY_WAIT_TIME); //wait to confirm renaming        6000ms
          if (destFile.exists())
          {
            renamed = true;
            break;
          }
        }
        catch (InterruptedException ie)
        {
          log.exception("File rename wait exception ", ie);
        }
      }

      if (renamed)
        log.info("Successfully renamed the file " + filename +
                            " to append .load at the end");
      else
      {
        log.error("Failed to verify renamed file " + filename + ".load"); //this is the error I get
              return;
      }
    }
    else
    {
      log.error("Unable to rename the file " + filename + " to append .load at the end");
      return;
    }
0
Comment
Question by:vakils
6 Comments
 
LVL 23

Expert Comment

by:Michael74
ID: 40454150
Try using Files.Move instead

String renameToFile = filename + ".load";
File sourceFile = new File(filename);
try {
     Files.move(sourceFile, sourceFile.resolveSibling(renameToFile));
} catch (IOException e) {
     log.error("Unable to rename the file " + filename + " to append .load at the end");
}

Open in new window


If your code only needs to be run on Linux another option would be to use Process Builder to run a Linux command such as mv although this method would be less than ideal.

https://docs.oracle.com/javase/6/docs/api/java/lang/ProcessBuilder.html
https://www.udemy.com/blog/rename-a-file-in-linux/
0
 
LVL 21

Expert Comment

by:Amitkumar Panchal
ID: 40454152
Check the location where the file is being created.

       // Rename the file with an appended .LOAD extension, so that next time
    // this program will not pickup the same file again
      String renameToFile = filename + ".load";             //filename is valid file name
      File sourceFile = new File(filename);
    if (sourceFile.renameTo(new File(renameToFile)))
    {
     //success, verify now
      File destFile = new File(renameToFile);
      System.out.println("File Path : "+ destFile.getAbsolutePath());
      boolean renamed = false;
      while (TIMES_TO_RENAME_VERIFY-- > 0)             //5 times
      {
        try
        {
          Thread.sleep(RETRY_WAIT_TIME); //wait to confirm renaming        6000ms
          if (destFile.exists())
          {
            renamed = true;
            break;
          }
        }
        catch (InterruptedException ie)
        {
          log.exception("File rename wait exception ", ie);
        }
      }

      if (renamed)
        log.info("Successfully renamed the file " + filename +
                            " to append .load at the end");
      else
      {
        log.error("Failed to verify renamed file " + filename + ".load"); //this is the error I get
              return;
      }
    }
    else
    {
      log.error("Unable to rename the file " + filename + " to append .load at the end");
      return;
    }
0
 

Author Comment

by:vakils
ID: 40454235
Sorry but I forgot to mention we are limited by Java 1.5
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 23

Accepted Solution

by:
Michael74 earned 250 total points
ID: 40454245
In that case it could be related to Bug ID 6213298
A DESCRIPTION OF THE PROBLEM :
After releasing a File object, another File object for the same file name cannot be renamed immediately.  Here's my work-around that usually works but still sometimes fails.
http://bugs.java.com/view_bug.do?bug_id=6213298

The link above has a work around but the solutions I posted should still work
0
 
LVL 14

Assisted Solution

by:Tommy Braas
Tommy Braas earned 250 total points
ID: 40455003
Use Runtime.exec(...)or  Apache Commons Exec to execute the shell command "mv" to move/rename your file. Keep in mind that this way of renaming/moving a file is not cross-platform.
0
 

Author Closing Comment

by:vakils
ID: 40456614
Thanks guys for your efforts. It seems best solution is to move out of Java 1.5
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

There is an easy way, in .NET, to centralize the treatment of all unexpected errors. First of all, instead of launching the application directly in a Form, you need first to write a Sub called Main, in a module. Then, set the Startup Object to th…
Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

910 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now