忙しすぎて死んでたゎ(´・ω・`)
んで放置してすみません(´;ω;`)
でも勉強なったゎ(´・ω・`)w
JavaでのFile操作が厄介だった(;´∀`)
今回ゎその1つの ファイル・フォルダを移動・コピーについて紹介するぜぇ( ゚д゚ )
今までだと
file.renameTo(oldFile)
だったけど
これだと上書きができなかったりする(´・ω・`)
移動する前に削除してもいいけど、削除もまた大変だからな^^;
※前回紹介
んで作ったのだ(´・ω・`)
/** * コピー元のパスから、コピー先のパスへ ファイルのコピーを行います。 * * @param srcPath * コピー元のパス * @param destPath * コピー先のパス * @throws IOException * IOException */ public static void copyTransfer(final String srcPath, final String destPath) throws IOException { copyTransfer(new File(srcPath), new File(destPath)); } /** * コピー元のファイルから、コピー先のファイルへ ファイルのコピーを行います。 * * @param src * コピー元のパス * @param dest * コピー先のパス * @throws IOException * IOException */ public static void copyTransfer(final File src, final File dest) throws IOException { if (src.isDirectory()) { // ディレクトリがない場合、作成 if(!dest.exists()){ dest.mkdir(); } String[] files = src.list(); for (String file : files) { File srcFile = new File(src, file); File destFile = new File(dest, file); copyTransfer(srcFile, destFile); } } else { // ファイルのコピー try (FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel();) { srcChannel.transferTo(0, srcChannel.size(), destChannel); } } }
これなら問題なし(`・ω・´)
移動ならコピーのあとに削除したらいいんだおwwww
この記事も参考にしてみてください。
Java File.renameTo() でエラーになった
哀れだ。Files.copy()で一発
返信削除コメントありがとうございます。
削除Filesは1.7から使えるのは知ってましたが、1.6だとってなってました。その後にFileUtilsを知ったのですがw
あとFilesはディレクトリの中身をすべてコピーしないと思います。。。