javaでディレクトリのcopy機能無かったから作ってみた。
今ファイル関係の処理を書いていたらふと思った。
そういえば、javaってディレクトリのcopy。ってか、ファイルのcopy機能無いよな。。。
てな訳で、この際だからバイト行く前に作ってみた。(jdk1.5以上で)
/** * @author ikki * */ class FileUtil { /** * @param src 送信元 * @param dest 宛先 * @throws IOException */ public static void copyFile(File src,File dest) throws IOException { if (src.isDirectory()) copyDirectory(src,dest); else copyTransfer(src.getPath(),dest.getPath()); } /** * @param srcPath 送信元 * @param destPath 宛先 * @throws IOException */ public static void copyTransfer(final String srcPath,final String destPath) throws IOException { FileChannel srcChannel = new FileInputStream(srcPath).getChannel(); FileChannel destChannel = new FileOutputStream(destPath).getChannel(); try { srcChannel.transferTo(0, srcChannel.size(), destChannel); } finally { srcChannel.close(); destChannel.close(); } } /** * @param srcPath 送信元 * @param destPath 宛先 * @throws IOException */ public static void copyDirectory(File src ,File dest) throws IOException { if (src.isFile()) copyFile(src,dest); if (!dest.exists()) dest.mkdir(); for (File ff : src.listFiles()) { String name = ff.getName(); if (name.equals(".") || name.equals("..")) continue; File d2 = new File(dest.getPath()+"/"+name); if (ff.isDirectory()) copyDirectory(ff,d2); else copyFile(ff,d2); } } }
とまあ、こんな感じです。
起きたてに書いたので、間違ってるかもしれませんが、まあその時は修正よろしくです。
では、早朝バイト行ってきます><