-2

I have a situation in which I want to copy the images from a directory to another directory. Also, I want the copied images to be stored with the different names. This is what I have done:

public static void main(String []args)
{
    File source = new File("/home/src");

    //rest of the code

    File[] listOfFiles = source.listFiles();
    for (int i = 0; i < listOfFiles.length; i++) 
    {
         File f = new File("/home/src/"+listOfFiles[i].getName());   //I want to copy all the images from src to dest
         boolean b1 = f.renameTo(new File("/home/dest/"+i+".jpg"));   

         //rest of the code

    }
}

Now, the problem is, when I'm running this code, the function renameTo() is renaming the images properly, but it is moving the images from "src" directory to "dest" directory. I don't want that to happen. I want all the images in "src" directory intact. So to achieve this, what I'm currently doing is, I'm using this code as it is and at the end I'm copying all the images back from "dest" to "src" using FileUtils.copyDirectory(). A lot of googling also didn't help. Is there any way of achieving it directly? Or I need to proceed with what I'm currently doing?

Siddharth M
  • 159
  • 1
  • 10

3 Answers3

4

What you are trying to do is to COPY the files. But that's not what renameTo does. Rather it MOVES or RENAMES them. The javadoc for renameTo explains this.

If you want to copy a file using classic Java, you open a FileInputStream for the source file, and a FileOutputStream for the destination file, and then copy the bytes from the input stream to the output stream.

For code examples, and for alternative ways of copying, read the answers to this Question:

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

What you need is to use

FileUtils.copyFile(File srcFile, File destFile);

from Apache's File Util

Ean V
  • 5,091
  • 5
  • 31
  • 39
1
    public static void main(String []args)
    {
        File source = new File("/home/src");

        //rest of the code
        File[] listOfFiles = source.listFiles();
        for (int i = 0; i < listOfFiles.length; i++) 
        {
             File f1 = listOfFiles[i];   //I want to copy all the images from src to dest
             File f2 = new File("/home/dst/"+listOfFiles[i].getName());

             FileUtils.copyFile(f1, f2);


        // code for copying the file from src to dest here

             boolean b1 = f2.renameTo(new File("/home/dst/"+i+".jpg"));   // this was corrected (to rename the destination file if you want)
             //rest of the code
        }
    }
4aRk Kn1gh7
  • 4,259
  • 1
  • 30
  • 41