Java目录操作

public class DirectoryDemo {

    public static void main(String[] args) {

    }

    /**
     * 判断文件是否存在
     */
    @Test
    public void Dir1() {

        String filePath = "D:\\news1.txt";
        File file = new File(filePath);
        if (file.exists()) {
           if (file.delete()) {
               System.out.println(filePath+"删除成功");
           } else {
               System.out.println(filePath+"删除失败");
           }
        } else {
            System.out.println(filePath+"文件不存在");
        }
    }

    /**
     * 判断目录是否存在
     * Java编程中,目录可理解为一种特殊的文件
     */
    @Test
    public void Dir2() {
        String filePath = "D:\\news1";
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println(filePath+"删除成功");
            }else {
                System.out.println(filePath+"删除失败");
            }
        } else {
            System.out.println("目录不存在");
        }
    }

    @Test
    public void Dir3() {

        String dirPath = "D:\\test\\demo";
        File file = new File(dirPath);
        if (file.exists()) {
            System.out.println(dirPath+"已经存在");
        } else {
            if (file.mkdirs()) { //mkdirs()创建多级目录,mkdir()创建一级目录
                System.out.println(dirPath+"已创建");
            } else {
                System.out.println(dirPath+"创建失败");
            }
        }
    }
}
posted @ 2022-08-06 20:59  jarico  阅读(40)  评论(0)    收藏  举报