當創建一個文件時,比如:E:\\test\\test.txt,此時若文件夾test不存在,那么直接創建文件會出錯,故首先要判斷文件夾是否存在,不存在的話要首先創建文件夾。
public class FileTest { public static void main(String[] args) { try {
File file = new File("E:\\test\\test.txt"); if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } if(!file.exists()){ file.createNewFile(); } } catch (IOException e) { // TODO e.printStackTrace(); } } }