JAvaはフォルダの下のすべてのファイルのコピーを実現します
ソースフォルダのすべてのファイルを含むフォルダ、ファイルフォルダのコピーを実現する実用的なクラスを退屈に書きました.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
public class Util {
public static int buffer_size = 2048;
private static void doCopy(File src, File dst) {
if (src.isFile()) {
try {
copyFile(src, dst);
} catch (IOException e) {
e.printStackTrace();
}
} else {
File dir = copyDirectory(src, dst);
File[] files = src.listFiles();
if (files.length == 0) {
} else {
for (File file : files) {
doCopy(file, dir);
}
}
}
}
public static void copy(File src, File dst) throws IOException {
if (!src.exists() || !dst.exists())
throw new FileNotFoundException();
else if (src.isFile() && dst.isFile())
copy(new FileReader(src), new FileWriter(dst));
else if (src.isDirectory() && (!dst.isDirectory()))
throw new IllegalArgumentException("Destination should be a directory!");
else {
doCopy(src, dst);
}
}
private static void copyFile(File src, File dst) throws IOException {
File file = new File(dst, src.getName());
copy(new FileReader(src), new FileWriter(file));
}
private static File copyDirectory(File src, File dst) {
File file = new File(dst, src.getName());
file.mkdir();
return file;
}
private static int copy(Reader in, Writer out) throws IOException {
int byteCount = 0;
try {
int bytesReader = -1;
char[] buffer = new char[buffer_size];
while ((bytesReader = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesReader);
byteCount += bytesReader;
}
out.flush();
} finally {
in.close();
out.close();
}
return byteCount;
}
}