14 Replies Latest reply: Jul 23, 2012 3:34 AM by sabre150 RSS

    Rename And Append To File

    884198
      Hi,

      I have a folder where i have many image files having names in format 001A0110.676

      My requirement is to rename these files. I have to remove . and append IW to the start of all filenames recursively. So my filename should be like IW001A0110676


      Please suggest how to implement this through java.

      Thanks
      Abhi
        • 1. Re: Rename And Append To File
          DrClap
          By using methods from the java.io.File class. In particular there's a listFiles() method which will give you an array of all files in a folder, and there's a renameTo() method whose function I leave for you to look up. A little bit of string manipulation and you're done.
          • 2. Re: Rename And Append To File
            884198
            Hi I have written below code to rename files i.e to append IW but i am not getting them renamed. can you tell me my mistake?
            public static void main(String args[])
                 { 
                      
                      try {
                              
                                
                             
                             
                             
                     // inputpath = args[0];
                     // outputpath = args[1];
                     
                              inputpath = "C:\\Test";
                         outputpath = "C:\\Test_out";
                     
                   
            
                               File f = new File(inputpath);
                               
                               
                               String[] catname = f.list();
                               
                               
                               System.out.println("Total Files Available To Rename = "+catname.length);
                              File[] listOfFiles = f.listFiles();
                                 for (int j = 0; j < listOfFiles.length; j++) {
                                      if (listOfFiles[j].isFile()) {
                                           String text = listOfFiles[j].getName();
                                           System.out.println(text);
                                      File F5=listOfFiles[j];
                                      System.out.println("F5 ="+F5);
                                      String text2="IW"+text;
                                      File F6= new File(text2);
                                      
                                      System.out.println(F6);
                                      
                                      F5.renameTo(F6)
                                      
                                      }}
            
                                            
                               
                              
                      }catch (Exception e){
                           System.out.println("Exception in Main :: "+e); 
                         System.exit(1);
                      }
                      
                 }
            }
            Edited by: sabre150 on Jul 22, 2012 12:06 PM

            Moderator action : added code tags to format the code. Next time you post code please add the { code} tags yourself.
            • 3. Re: Rename And Append To File
              sabre150
              From your code I deduce that you don't just want to rename the files but to create a copy of them with a different name in a different directory. Is this correct?

              When posting you need to be much more precise about your requirements.
              • 4. Re: Rename And Append To File
                884198
                I will be more specific from future. Let me define to you what exactly my requirement is.

                I have a folder in which there are tiff images.The naming convention of these tiff images are like 001A0110.676

                I have to rename these images name by appending IW to all and removing . from all.

                I require output name as IW001A0110676.Likewise i want to rename all images and put them all in an output folder.

                Can you help me in this regard?

                thanks
                • 5. Re: Rename And Append To File
                  sabre150
                  To save having to do all the work yourself take a look at the library http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html .
                  • 6. Re: Rename And Append To File
                    rp0428
                    >
                    have a folder in which there are tiff images.The naming convention of these tiff images are like 001A0110.676

                    I have to rename these images name by appending IW to all and removing . from all.

                    I require output name as IW001A0110676.Likewise i want to rename all images and put them all in an output folder.
                    >
                    That still isn't clear.
                    1. When you are done will you still have a copy of the files in the orginal directory? Will the names of these files be the new names or the old names?
                    2. When you are done will lyou have a copy of the files in the new directory? Will the names of these files be the new names or the old names?

                    Your code suggests you are doing this on windows.

                    I would suggest using the OS to COPY the files and then use Java code to rename them. If you are leaving a copy in the original directory and these should have the new name then do the rename first and leave the files there. Then us the OS to COPY the files.

                    You cannot use an OS command to remove the '.' but you can use an OS command to add the IW
                    E:\>copy aafile\*.* aafile1\IW*.*
                    The above command will copy ALL the files and prefix the file names with IW. Then you could use Java to rename them to remove the '.'

                    Or just do the copy after renaming them.

                    See this example of using a Process to execute a command line
                    http://stackoverflow.com/questions/8963413/how-to-run-windows-commands-in-java-and-return-the-result-text-as-a-string

                    It uses code that includes
                    Process p=Runtime.getRuntime().exec("cmd /c dir");
                    p.waitFor();  
                    • 7. Re: Rename And Append To File
                      sabre150
                      Though one can use Runtime.exec() ( or ProcessBuilder) for this task it is hard to justify it when there are very good platform independent libraries to do the Job.
                      • 8. Re: Rename And Append To File
                        DarrylBurke
                        Cross posted
                        http://www.java-forums.org/new-java/61580-append-renaming-file.html

                        db
                        • 9. Re: Rename And Append To File
                          rp0428
                          >
                          Though one can use Runtime.exec() ( or ProcessBuilder) for this task it is hard to justify it when there are very good platform independent libraries to do the Job.
                          >
                          For the COPY part I disagree; don't reinvent the wheel. The OS has always had the COPY functionality built-in, it uses native code, that code has been thoroughly tested and it is well supported. I find it hard to believe that any of those 'independent' libraries are going to be anywhere near as efficient at copying a folder as the native code of the OS. And they certainly aren't going to be as thoroughly tested or as well supported.

                          For the RENAME part I would agree and for the same reason; don't reinvent the wheel. If you have access to a 3rd party library you have confidence in then use it. If you don't then write your own. There isn't a lot of risk in renaming especially if you are renaming a copy.

                          But leave any COPY work to the OS.
                          • 10. Re: Rename And Append To File
                            sabre150
                            rp0428 wrote:
                            >
                            Though one can use Runtime.exec() ( or ProcessBuilder) for this task it is hard to justify it when there are very good platform independent libraries to do the Job.
                            >
                            For the COPY part I disagree; don't reinvent the wheel. The OS has always had the COPY functionality built-in, it uses native code, that code has been thoroughly tested and it is well supported. I find it hard to believe that any of those 'independent' libraries are going to be anywhere near as efficient at copying a folder as the native code of the OS. And they certainly aren't going to be as thoroughly tested or as well supported.
                            Ouch! The efficiency of any file copy will depend on the basic native disk access routines supplied by the underlying OS and Java will use the same routines as the COPY command. What Runtime.exec() will add is the cost of starting the new process to invoke the COPY command. So as to avoid the traps associated with Runtime.exec() (see http://www.javaworld.com/jw-12-2000/jw-1229-traps.html ) it will also require more code than you have posted.

                            >
                            For the RENAME part I would agree and for the same reason; don't reinvent the wheel. If you have access to a 3rd party library you have confidence in then use it. If you don't then write your own. There isn't a lot of risk in renaming especially if you are renaming a copy.
                            Ouch again! I really don't get this. So why then did Sun supply the File.rename() method when one can do the work though Runtime.exec() ?

                            >
                            But leave any COPY work to the OS.
                            When implemented through Runtime.exec() this is just wrong. Both the copy and the rename can be done in pure Java in very few lines of code and I'm willing to bet that they take less time than using Runtime.exec() since Runtime.exec() has to start a new process. The pure Java solution will behind the scenes delegate to the same OS 'C' methods but will be platform neutral rather than platform specific.

                            I have used Runtime.exec() ( and ProcessBuilder since Java 5 ) extensively over more than 10 years of using Java but to me it is the last resort and not the first resort as you seem to think. I'm not willing to debate this any further and I will leave it to the readers of this thread to judge the merits of Runtime.exec() approach for the OP's task.
                            • 11. Re: Rename And Append To File
                              EJP
                              Windows (and OS/2 and probably MS.DOS) provides a file-copy system call. The data doesn't have to traverse the kernel/user boundary at all. COPY.EXE and XCOPY.EXE either do or should use this and if so they will be considerably faster than a C program that doesn't, which in turn will be considerably faster than a Java program that doesn't use NIO with direct byte buffers, as there is the JNI/Java boundary to be crossed as well. All these boundaries imply data copying.

                              Further, the system call I described accepts wildcards, so it also saves you all the directory processing as well.
                              • 12. Re: Rename And Append To File
                                sabre150
                                EJP wrote:
                                Windows (and OS/2 and probably MS.DOS) provides a file-copy system call. The data doesn't have to traverse the kernel/user boundary at all. COPY.EXE and XCOPY.EXE either do or should use this and if so they will be considerably faster than a C program that doesn't, which in turn will be considerably faster than a Java program that doesn't use NIO with direct byte buffers, as there is the JNI/Java boundary to be crossed as well. All these boundaries imply data copying.

                                Further, the system call I described accepts wildcards, so it also saves you all the directory processing as well.
                                So are you saying that YOU would use Runtime.exec() or ProcessBuilder to perform this task because it is likely to be more efficient in speed and code than using pure Java ?
                                • 13. Re: Rename And Append To File
                                  EJP
                                  You know the answer to that! I've said it 100 times here. Any post that starts out 'so are you saying' is 99% likely to be wrong.* Another confirming instance.

                                  In this particular circumstance I would ask why I am writing a program at all. Why do the files have the wrong names, and why can't we fix that at the source? or possibly it is a one-off requirement, in which case I would run ls > x;vi x; sh x, or the Windows equivalent.
                                  • 14. Re: Rename And Append To File
                                    sabre150
                                    EJP wrote:
                                    You know the answer to that! I've said it 100 times here. Any post that starts out 'so are you saying' is 99% likely to be wrong.* Another confirming instance.
                                    Of course I knew the answer and pretty much knew how you would react but I was trying to make it clear to readers not so familiar with your posts.