JAvaはcopyフォルダ機能を実現
2966 ワード
Javaでフォルダの内容を別のフォルダにコピーする機能を実現
/**
* A class of dealing file
*
* @author Meng Wang
*
*/
public class FileDeal {
/**
* copy all files of a file path to another file path
*
* @param fromFilePath
* @param toFilePath
*/
public void copyFileDir(String fromFilePath, String toFilePath) {
File fromFileDir = new File(fromFilePath);
File toFileDir = new File(toFilePath);
// if new File Path is not exist,create it.
if (!toFileDir.exists()) {
toFileDir.mkdirs();
}
boolean isToFileSeparetor = isFileSeparetor(fromFilePath);
boolean isFromFileSeparetor = isFileSeparetor(toFilePath);
String[] childFileList = fromFileDir.list();
for (String childFileString : childFileList) {
File childFile = new File(fromFileDir.getPath() + File.separator
+ childFileString);
String fileName = childFile.getName();
if (!childFile.isDirectory()) {
try {
FileInputStream fileInputStream = new FileInputStream(
childFile);
File toFile;
if (isToFileSeparetor) {
toFile = new File(toFilePath + fileName);
} else {
toFile = new File(toFilePath + File.separator
+ fileName);
}
FileOutputStream fileOutputStream = new FileOutputStream(
toFile);
byte[] b = new byte[1024];
try {
while (fileInputStream.read(b) != -1) {
fileOutputStream.write(b);
}
fileInputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.err.print(e);
}
} else {
String childFromFilePath = null;
String childToFilePath = null;
childFromFilePath = isFromFileSeparetor ? fromFilePath
+ fileName : fromFilePath + File.separator + fileName;
childToFilePath = isToFileSeparetor ? toFilePath + fileName
: toFilePath + File.separator + fileName;
copyFileDir(childFromFilePath, childToFilePath);
}
}
}
/**
* if the filePath is end with fileSeparetor sign
* @param toFilePath
* @return
*/
public boolean isFileSeparetor(String filePath) {
if (filePath.lastIndexOf(File.separator) == filePath.length() - 1) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
FileDeal fileDeal = new FileDeal();
fileDeal.copyFileDir("E:\\my space", "E:\\wang space");
}
}