JAVA用File创建一个多级目录a/b/c/d/e/f,然后在每一个目录里面添加一些文件和目录

嗯,就是不知道怎么在每一个目录里面去添加一些文件,求解答,谢谢

以下为一些基本操作

import java.io.*;

public class Test {

    public static void main(String[] args) throws IOException {
        File file = new File("D:/test/a/b/c/d");
        if (!file.exists()) {
            // 创建文件夹,上级目录不存在时自动创建,使用file.mkdir()方法时上级目录不存在会抛异常
            file.mkdirs();
        }

        File file2 = new File("D:/test/a/b/c/d/test.txt");
        if (!file2.exists()) {
            // 在D:/test/a/b/c/d/下创建一个新文件
            file2.createNewFile();
        }

        File file3 = new File("D:/test/a/b/c/c-child");
        if (!file3.exists()) {
            // 在D:/test/a/b/c/下创建一个新文件夹c-child
            file3.mkdir();
        }

        // 在D盘根目录下创建一个文件test.txt并写入一下内容
        // 将D:/test.txt复制到D:/test/a/b/c/下并重命名为copy.txt
        copyFile(new File("D:/test.txt"), new File("D:/test/a/b/c/copy.txt"));
    }

    /**
     * 文件复制
     *
     * @param source 源文件
     * @param target 目标路径
     * @throws IOException
     */
    public static void copyFile(File source, File target) throws IOException {
        try (FileInputStream ins = new FileInputStream(source);
             FileOutputStream out = new FileOutputStream(target)) {
            byte[] b = new byte[1024];
            int n;
            while ((n = ins.read(b)) != -1) {
                out.write(b, 0, n);
            }
        }
    }
}

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答