Monday, May 3, 2010

Iterating Over Files and Writing in Another Directory -- Java

Below is the sample code for iterating over all the files in a directory and copying them to another place.


package com.learn;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;


public class CopyFile {

public static void main(String[] args) {
try {
System.out.println("==================");
File dir = new File("/your/directory/path/");

File newDir = new File(dir.getAbsolutePath() + "/copy");
newDir.mkdir();

File[] files = dir.listFiles();
for (File file : files) {
if (!file.isDirectory()) {
FileReader in = new FileReader(file);
FileWriter out = new FileWriter(newDir.getAbsolutePath() + "/" + file.getName());
int c;
while ((c = in.read()) != -1)
out.write(c);

in.close();
out.close();
System.out.println(file.getName() + " is copied ");
}
}
System.out.println("==================");
} catch (Exception e) {
e.printStackTrace();
}
}

}

No comments: