General discussion

Locked

moving files in java

By ashapoo_jain ·
I want to move files from one folder to another in Java. I used the renameTo method in the File class but that doesnt helps me...
Am posting my code here, can some one look at it and tell me whats wring in it and also is there an efficient way to move files in Java across folders...

public boolean moveFiles(String source, String destination)
{
//This method moves the files from one directory to another
File sourceDir = new File(source.trim());
File destinationDir = new File(destination.trim());

boolean created = true;
if(!destinationDir.exists())
{
//Create that directory

created = destinationDir.mkdir();
System.out.println("The directory created " + created);

//do the moving of files here

File [] tmp = sourceDir.listFiles();
for(int i =0;i<tmp.length;i++)
{
System.out.println(tmp.getName());
tmp.renameTo(destinationDir);
}
return true;
}
else
{
//the directory already exists and start moving the files from the directory to the other one......
System.out.println("The directory already exists and there is no need for recreation");
File [] tmp = sourceDir.listFiles();
for(int i =0;i<tmp.length;i++)
{
System.out.println(tmp.getName());
tmp.renameTo(destinationDir);
}
return true;
}



}

This conversation is currently closed to new comments.

3 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

moving files in java

by sgovindu In reply to moving files in java

renameTo seems not to work with driectories. In your loop of renameTo try the following:

for(int i = 0; i < tmp.length; i++)
{
File newFile = new File(destinationDir, tmp.getName());
tmp.renameTo(newFile);
}

Collapse -

moving files in java

by ashapoo_jain In reply to moving files in java

Poster rated this answer

Collapse -

moving files in java

by ashapoo_jain In reply to moving files in java

This question was closed by the author

Back to Web Development Forum
3 total posts (Page 1 of 1)  

Related Discussions

Related Forums