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

  • Post author:
  • Post category:java


展开全部

以下为32313133353236313431303231363533e4b893e5b19e31333365663439一些基本操作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);

}

}

}

}



版权声明:本文为weixin_39630855原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。