不知道“文件”和“文件路径”是否存在的处理情况
1.如果是文件,先获取文件父路径,没有就生成父路径,然后再生成文件。
1 public class TestMain { 2 3 public static void main(String[] args) { 4 // 文件和文件夹都不存在的情况 5 File file = new File("D:\\aa\\bb\\cc.txt"); 6 // 1.判断文件的父文件夹是否存在 7 File parent = new File(file.getParent()); 8 if (!parent.exists()) { 9 System.out.println("父文件夹不存在创建"); 10 // 注意:mkdirs 带 s 表示创建多层文件夹(不存在的一路创建过来)。 11 parent.mkdirs(); 12 try { 13 boolean b = file.createNewFile(); 14 if (b) { 15 System.out.println("创建文件成功"); 16 }else{ 17 System.out.println("创建文件失败"); 18 } 19 } catch (IOException e) { 20 System.out.println("创建文件失败"); 21 } 22 } 23 24 }
2.如果父路径存在,就判断文件是否存在,不存在就生成文件。
1 public class TestMain { 2 3 public static void main(String[] args) throws IOException { 4 // 文件不存在的情况 5 File file = new File("D:\\aa\\bb\\cc.txt"); 6 // 1.判断文件的父文件夹是否存在 7 File parent = new File(file.getParent()); 8 if (!parent.exists()) { 9 System.out.println("父文件夹不存在"); 10 }else{ 11 System.out.println("父文件夹存在"); 12 if (!file.isDirectory()) { 13 boolean b = file.createNewFile(); 14 if (b) { 15 System.out.println("文件创建成功"); 16 }else{ 17 System.out.println("文件创建失败"); 18 } 19 }else{ 20 System.out.println("文件存在"); 21 } 22 } 23 } 24 }