Java 判断文件夹和文件是否存在并创建 - 代码示例
你可以使用 Java 的 File 类来判断文件夹和文件是否存在,并使用 mkdirs() 方法来创建文件夹,使用 createNewFile() 方法来创建文件。下面是一个示例代码:
import java.io.File;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
String folderPath = "/path/to/folder";
String filePath = "/path/to/file.txt";
// 判断文件夹是否存在,不存在则创建
File folder = new File(folderPath);
if (!folder.exists()) {
boolean success = folder.mkdirs();
if (success) {
System.out.println("文件夹创建成功");
} else {
System.out.println("文件夹创建失败");
}
}
// 判断文件是否存在,不存在则创建
File file = new File(filePath);
if (!file.exists()) {
try {
boolean success = file.createNewFile();
if (success) {
System.out.println("文件创建成功");
} else {
System.out.println("文件创建失败");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
在上面的示例代码中,你需要将 /path/to/folder 替换为你想判断和创建的文件夹路径,将 /path/to/file.txt 替换为你想判断和创建的文件路径。
原文地址: http://www.cveoy.top/t/topic/bna8 著作权归作者所有。请勿转载和采集!