java实现move操作

java实现move操作

这类操作与文件所在的文件系统息息相关.

File的renameTo一般只用于同级目录修改文件名。

想要多级目录移动文件还得用Files.move方法。

同一个文件系统下会进行move操作

不同文件系统,则通过拷贝-删除的方式实现move。

package io.move;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * move-test<br/>
 * ├── dir1<br/>
 * │   └── child<br/>
 * │       └── hui3<br/>
 * └── hui1<br/>
 * <p>
 * move-test<br/>
 * ├── dir1<br/>
 * │   └── child<br/>
 * │       └── hui3<br/>
 * └── hui2<br/>
 */
public class MoveTest {
    public static void main(String[] args) {

        String root = "/Users/ephuizi/move-test";

        Path test1 = Paths.get(root, "hui1");
        Path test2 = Paths.get(root, "hui2");

        File test1File = test1.toFile();
        File test2File = test2.toFile();
        //同文件系统,同级目录下,文件重命名
        test1File.renameTo(test2File);

        Path test3 = Paths.get(root, "dir1");
        Path test4 = Paths.get(root, "dir2");

        try {
            //多级目录下文件move
            mvoeDir(test3.toFile(), test4.toFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void mvoeDir(File from, File to) throws IOException {

        File[] children = from.listFiles();
        for (File child : children) {
            Path target = Paths.get(to.getPath(), child.getPath().substring(from.getPath().length()));
            if (child.isDirectory()) {
                File targetFile = target.toFile();
                if (!targetFile.exists()) {
                    Files.move(child.toPath(), target);
                } else {
                    if (targetFile.isFile()) {
                        targetFile.delete();
                    }
                    mvoeDir(child, targetFile);
                }
            } else if (child.isFile()) {
                //
                Files.move(child.toPath(), target, StandardCopyOption.REPLACE_EXISTING);
            }
        }
    }

    private static void delDir(File dir) {
        File[] children = dir.listFiles();
        for (File child : children) {
            if (child.isDirectory())
                delDir(child);
            else
                child.delete();
        }
    }
}

 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.