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.

Similar Messages

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

  • 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

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

  • 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

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

  • 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

    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

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

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

  • File renameto issue

    I have been tracking this down for a couple of days now and thought I would ask the forum for their input.
    I have a very simple process that opens a file, reads in the data, writes some data to a DB, and them moves the file to a processed folder.
    SOME of the instances I have running that are performing this process are moving the files into the wrong directory. I am going round and round with this
    being an OS issue and/or jvm issue. The oddest thing is that the wrong directory that some of the processes write their files to is always the last
    directory created under that particular filesystem.
    System:
    sun-jdk-1.5.0.06
    Linux; SMP; 2.6.12
    Process is run via shell script every 10 minutes where a directory is passed to the process, the process then looks in the directory for files,
    does what it does, and then renames the file. ex. "LogProcessor /var/log/10.5.1.2/". The process should move the file to the folder /var/log/10.5.1.2/processed,
    instead it is moving the file to "/var/log/10.5.1.52/processed". All of the debug code you see below is telling me that everything is what and where it should
    be, however, it is not.
    Other information: There are about 15 independent processes running started by separate shell scripts and all should be reading and writing to their respective folders.
    Any input would be greatly appreciated.
    CODE:
    File dirName = new File(args[0]);
    String[] files = dirName.list();
    //test if directory actually has something we want
                   if (files != null) {
                        // loop through list of files found in directory
              for (int i=0; i<files.length; i++) {
              // Get filename of file or directory
                   if(debug)
                        System.err.println("File Extension: " + files.substring(files[i].length() - 3));
                   // test last 3 characters for file extension we need
                   if (files[i].substring(files[i].length() - 3).equalsIgnoreCase("log") || files[i].substring(files[i].length() - 3).equalsIgnoreCase("alm")) {
              fileName = args[0] + files[i];
                   // Call each method respectively passing in all the local objects
                   if (alarms) {
                                       logProcessor.alarmsProcessor(fileName, logFile, job, jobActions, errors, debug);
                                  } else {
                                       logProcessor.storeLogsProcessor(fileName, logFile, job, jobActions, errors, debug);
                   //SLD 11/28/2007: move the file to the processed folder after read
                   File file1 = new File(fileName); //this file already existed on the file system
                   File file2 = new File(args[0]+"processed/"+files[i]);
                        if (file1.renameTo(file2)) {
                             System.out.println("File "+files[i]+" Moved to processed folder "+ args[0] + "processed" + file2.toString());
                             System.out.println("From: " + file1.toString() + " To: " + file2.toString() );
                        } else {
                             System.out.println("File "+files[i]+" NOT Moved to processed folder "+ args[0] + " due to either permissions, folder nonexistant or file already exists");

    Well, just to update the issue. The problem has been solved. There was an entry into the list of IP's that was 10.58.?.??, which in the unix world is a special character/place holder for all
    files/folders that resemble it. This was wreaking havoc on my java program when moving files.
    Thanks,

  • Class File - renameTo problem

    hi all!
    Environment:
    OS: Windows XP
    Filesystem: NFS
    JRE: jre1.5.0_04
    I have the following code:
    File logfile = new File(new File(this.lpLogDir), this.lpFileName);
              if( logfile.exists() ) {
                   if( logfile.renameTo(new File(new File(this.lpLogDir), (Calendar.getInstance()).getTimeInMillis() + "." + this.lpFileName)) ){
                        System.out.println("File renamed to " + new File(new File(this.lpLogDir), (Calendar.getInstance()).getTimeInMillis() + "." + this.lpFileName).getAbsolutePath());
                   }else {
                        System.out.println("Could not rename the file to " + new File(new File(this.lpLogDir), (Calendar.getInstance()).getTimeInMillis() + "." + this.lpFileName).getAbsolutePath());
                   System.out.println(logfile.getName());My problem: the file is not renamed after this operation. The renameTo() method returns true, but the getName() prints the old file name. Any suggestions?
    cheers
    dian

    renameTo does NOT change logfile. It still points the abstract file "this.lpLogDir "/" this.lpFileName". What it does it moves the content in the concreate file logfile to a new location.

  • Step by Step Guide Details for RFC to File and File to RFC scenario

    Hi Guru's
    Good day to you. I am tyring to develop some scenarios based on RFC adaptor. so i want to start up with basic scenarios like RFC to File  scenario(Here i just want to pull some data from SAP using RFC and put it in destination folder as an text file) and FILE to RFC scenario (Here i just want to take some data from the file and update into SAP).
    For doing these scenarios i would like to request you people to send me the step by step guide which explains me about the complete steps of configurations required to do the RFC to FILE scenario and FILE to RFC scenario.
    I found some scenarios and i am in confused state. so i request you to please put your experience to help me out.
    thanks in advance.
    Regards
    Raj

    Hi Aaron,
    I don't know your scenario and your ECC and PI versions but I learned how to use ABAP Proxy more than 1 year ago with the following tutorial:
    Edit--> The forum doesn't allow me to post external link, just search "ABAP Proxy Communication Scenario" in google and visit the 1st result
    The way to develop ABAP Proxys has changed a little if your PI is 7.1. In the ECC side, the transaction SPROXY looks much better too if you have a recent version of the ECC.
    Edited by: Marshal on Oct 8, 2009 5:08 PM
    I've found that SDN Document. Maybe the scenario is not the most simple to start with ABAP Proxy but is very well documented and is for PI 7.1. The document also handles the inbound and outbound proxys
    [http://www.sdn.sap.com/irj/scn/index?rid=/library/uuid/c00ca32e-f991-2b10-f5be-97114bd2b08f&overridelayout=true]
    Edited by: Marshal on Oct 8, 2009 5:22 PM

Maybe you are looking for