以下为一些基本操作
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)
}
}
}
}
//创建多级目录public File createMultilevelDirectory(String[] directories,String rootPath) {
if (directories.length == 0) {
return null
}
File root = new File(rootPath)
for (int i = 0i <directories.lengthi++) {
File directory = new File(root, directories[i])
directory.mkdir()
root = directory
}
return root
}
创建带有多级目录的文件
public File createFileWithMultilevelDirectory(String[] directories,String fileName,String rootName) throws IOException {
//调用上面的创建多级目录的方法
File filePath = createMultilevelDirectory(directories,rootName)
File file = new File(filePath,fileName)
file.createNewFile()
return file
}
试试:
public static void main(String[] args) throws IOException {
String separator = File.separator
String T = "A"+separator+"B"+","+"A"+separator+"E"
System.out.println(T)
String[] paths = T.split(",")
for(int i=0i<paths.lengthi++){
System.out.println("**"+"E:\\"+paths[i])
File file = new File ("E:\\"+paths[i])
file.mkdirs()//我原来用mkdir(),说不到路径。原因:这里要同时生成A 和B两个文件夹
//原来E:\下没有A,如果已经有A文件夹,则用mkdir()
}
}