|
本帖最后由 Pant1980 于 31.8.2009 23:46 编辑
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class FolderCopy {
public static void main(String[] args) {
copyFolder("C:\\Brother", "c:\\temp\\brother2", "c:\\record.txt");
}
public static void copyFolder(String src, String des, String recordFilePath) {
File srcFolder = new File(src);
File desFolder = new File(des);
desFolder.mkdirs();
try {
OutputStream os = new FileOutputStream(recordFilePath);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.append(des);
bw.newLine();
copyRecursive(srcFolder, desFolder, bw, 0);
bw.close();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void copyRecursive(File srcFolder, File desFolder, BufferedWriter bw, int level) {
// One time this function called, it is one level deeper.
level++;
for(File file : srcFolder.listFiles()) {
// Depth first write the copy information to the record file.
writeIndent(bw, level);
try {
if(file.isDirectory()) {
bw.append("+");
}
bw.append(file.getName());
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
if(file.isDirectory()) { // Create sub folder.
String subDesFolderPath = desFolder.getAbsolutePath()
+ "\\" + file.getName();
File subDesFolder = new File(subDesFolderPath);
subDesFolder.mkdir();
// Recursive copy the subfolder.
copyRecursive(file, subDesFolder, bw, level);
} else { // Do copy.
String desFilePath = desFolder.getAbsolutePath()
+ "\\" + file.getName();
try {
OutputStream os = new FileOutputStream(desFilePath);
InputStream is = new FileInputStream(file);
int byteread = 0;
byte[] buffer = new byte[1024];
while((byteread = is.read(buffer)) != -1) {
os.write(buffer, 0, byteread);
}
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void writeIndent(BufferedWriter bw, int level) {
try {
for (int i = 0; i < level; i++) {
bw.append("\t");
}
} catch (IOException e) {
e.printStackTrace();
}
}
} |
评分
-
1
查看全部评分
-
|