How to copy files from one directory to another directory
Hello, i may be asking very small question, but i could nt find how to do ? Anyways lemme give my code for copying all the files from one directory to another
public class CopyingFile {
static File source = new File("/home/dev06/File/sourcefolder");
static File destin = new File("/home/dev06/File/destinationfolder");
public void copyFile(File source, File dest) throws IOException {
if (source.isDirectory()) {
String[] children = source.list();
for (int i = 0; i < children.length; i++) {
copyFile(new File(source, children[i]), new File(destin,
children[i]));
}
} else {
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(destin);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
public static void main(String[] args) throws IOException {
CopyingFile c = new CopyingFile();
c.copyFile(source, destin);
}
}
with my above code i was able to copy all the files from source to destin - now my query is i want copy only a list of files which are less than 1MB - and i want delete those copied files in source :)
any help will be appreciated
Re: How to copy files from one directory to another directory
You can get the children as an array of File rather than String. That way you can check the size of a child file before calling copyFile() with it.
Also if you are going to remove the source you could possibly use the File renameTo() method.
Re: How to copy files from one directory to another directory
Read the File class in Java SE documentations.
Re: How to copy files from one directory to another directory
Yep i found it by using org.apache.commons.io.FileUtils class
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class FileMover extends FileSystem {
File sourceFile = new File("/home/dev06/File/sourcefolder");
File destinationDir = new File("/home/dev06/File/destinationfolder");
public void findFiles() throws IOException {
for (File files : sourceFile.listFiles()) {
if (files.length() > 50) {
FileUtils.moveFileToDirectory(files, destinationDir, true);
}
else{
System.out.println("files less than 50"+files);
}
}
}
public static void main(String[] args) throws IOException {
FileMover fileMover = new FileMover();
fileMover.findFiles();
}
}
-> this will move all the files which are greater than 50bytes to amy destination directory
Re: How to copy files from one directory to another directory
Good Luck. And read FAQ to know how to post codes on forums.