Solved

Rename file in Java

Posted on 2014-11-19
6
410 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 20

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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Having just graduated from college and entered the workforce, I don’t find myself always using the tools and programs I grew accustomed to over the past four years. However, there is one program I continually find myself reverting back to…R.   So …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This video teaches viewers about errors in exception handling.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

758 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

25 Experts available now in Live!

Get 1:1 Help Now