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.

Similar Messages

  • 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

  • Why java file name and class name are equal

    could u explain why java file name and class name are equal in java

    The relevant section of the JLS (?7.6):
    When packages are stored in a file system (?7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:
    * The type is referred to by code in other compilation units of the package in which the type is declared.
    * The type is declared public (and therefore is potentially accessible from code in other packages).
    This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.
    When packages are stored in a database (?7.2.2), the host system must not impose such restrictions. In practice, many programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.

  • 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.

  • HT203167 Why do files that I have organized into folders not stay in their folders after closing and reopening iTunes? And Why does the renaming get undone? I do this in iTunes Media/ Music.

    Why do files that I have organized into folders not stay in their folders after closing and reopening iTunes? And Why does the renaming get undone? I do this in iTunes Media/ Music.

    I recently had to reinstall my software for a
    dell computer a dell latitude d 830, then after installing all of my software and such including itunes the player did well even record to disks with no problems now that my system has done alot of updating of system files....now the itunes does not burn to my cd...error message 2131 this time
    The 2131 usually indicates firmware needs to be updated on a drive.
    Head to your drivers and downloads page for your latitude at Dell, and check for updates to your firmware for your optical drives. If you're behind and you update, does that clear up the 2131?

  • In CS6, why the file size remains same after croping? And how do I reduce the size after each cropin

    In CS6, why the file size remains same after croping? And how do I reduce the size after each croping? Thx

    Select the Crop Tool and check the box [  ] Delete Cropped Pixels and you should see a reduction in file size.  With the box unchecked, the data is still maintained in the document, you just can't see it.
    -Noel

  • Why is File Vault is useful?

    I have File Vault but do not understand it or its usefulness.  Can I deactivate it and if so what happens?
    Why is File Vault useful?
    Thanks.

    File Vault 2 was the only incentive for me to upgrade to Lion, since it's not natively supported in Snow Leopard.  Our company requires encryption of sensitive data, so I created a separate partition and used the disk utility command
    diskutil cs convert diskN -passphrase (the partition identification "diskxsy" is provided in Disk Utility via the Info command in the menu bar)
    to encrypt the new volume, which can now be accessed seamlessly from within Lion.  I didn't encrypt my home folder, however, since my configuration (SSD OptiBay & HDD for storage) isn't currently supported.  The link below discusses this issue and provides a fix, but I'm hoping a future Lion update will support File Vault encryption of home directories located on system-external drives (which is often the case for MacBook Air users).
    https://github.com/jridgewell/unlock

  • 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

  • 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

  • Why the file not picked by PI

    Hi mates:
           I tried to implement a XML-to-XML senario by XI, it is like picking the file from one folder to another .  and I have created and configurated everything for senario in ID and IR. and activated everything. but the file won't be picked up by XI, 
          I used two computers for the senario, one for Xi, one for the business system.
          Could you please tell me why the file can't be picked up by XI. do I have to installed any FTP server
    on the business system?
          Thank you very much!

    Hi Jingying,
                  There is some reasons are happended for the file is not picking.
    1) If use FTP , Check your FTP Connection working or not
    2)If not pick the file to XI , Check data from source end, if it wrong its shows the error in RWB->Communication Channel Monitoring--> File adapter..
    3)Check the sender Communication channel configured properly or not.
    Regards,
    Sateesh N.

  • Why are files to large to play on my pc. its an over spec gaming rig

    why are files to large to play on my pc. its an over spec gaming rig

    itunes 11 seams to have fixed issue

  • 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);
    }

  • Why do files from my Nikon D200 camera which are shot at 28MB come into Aperture at only 7MB?

    Why do files from my Nikon D200 camera which are shot at 28MB come into Aperture at only 7MB?
    I had these images in Large Fine JPG format at 28MB but when imorted and started working with them they are only & MB files in Aperture?

    Léonie,
    honestly speaking, I have done most of my image adjustments since 2006 (when I bought the D200) in various image processing applications (e.g. Capture One, Bibble 5 - now turned to AfterShot Pro by Corel, Lightroom at a friend's PC). I also tried Nikon's Capture NX but never liked it. Speaking of images that have been worth while keeping and working with as a RAW file I never saw any difference. As far as I can say with respect to Aperture 3 I come to the the same result as I did with the other software.
    People may say that with the disk space being so cheap now it is not worth while thinking about that. But there is one other aspect that can be of advantage in certain situations: The compressed RAWs are transferred faster to and from the the card than the uncompressed files. Also, the time for decompression in applications seems to be shorter than that saved while reading the smaller files.
    Before I started to use the compression feature (which in fact should be not lossless in the case of D200) I studied some reviews on that, of course.
    Citing one of them one could say
    "I tried to make duplicate shots to compare. I gave up. The mechanical exposure repeatability of my camera and nature itself aren't stable enough to let me make two captures close enough to see any possible difference between compressed and uncompressed raw.
    People do see differences. They are seeing fluctuations in their technique shot-to-shot, not any differences due to the compression."
    by Ken Rockwell
    If you are interested, here is the original article by Ken Rockwell.
    Another very elaborate investigation can be found here.
    Again, a quote from the controversal discussion on that comparison:
    "The ‘lossy’ NEF compression is really a clever use of information theory to save space by eliminating redundant raw levels. The noise which is unavoidably present in light effectively dithers tonal transitions so that the compression is *perceptually lossless*."
    by a poster named emil
    As far as I have read elsewhere, newer cameras as the D300 even have really "lossless" compression algorithms.
    Cheers,
    Michael

Maybe you are looking for

  • After upgrading to iOS 7.0.2....big problem

    After upgrading to iOS 7.0.2 my phone always show me to connect to iTunes to use push notifacations,and I cannot sign in my FaceTime oso

  • Multiple Users Can't Access Time Capsule Data

    My wife and I have two separate Apple MacBooks that share a Time Capsule. We have different account names on these respective computers. I initially set up my Time Capsule and created folders that I can access from Finder.app when I connect over our

  • Reference condition rebate

    Hi Sap gurus! I have a rebate condition, ZBO3, and a reference condition of that, ZZO3 in the same sales pricing procedure. I have two agreements for the same condition rebate, ZBO3. When I create a billing document, it finds and displays the two agr

  • Metadata Uneditable in MS Windows

    This may be a Mac vs PC thing, not specific to Aperture, but when I export versions from Aperture and copy them to my wife's PC she is unable to edit the file "properties". In Windows the properties are things like title, caption, and comments.  It t

  • Hooking up analog 5.1 speakers to dvd through ext

    is it possible to achieve surround sound dvd playback by connecting my dvd player to the extigy's digital connection and the speakers to the analog connection? or is there any other configuration that would allow me to use the speakers with my dvd pl