在磁盘创建文件夹和文件时报错:Exception in thread “main“ java.io.IOException: 系统找不到指定的路径。请问我就想在D盘创建一个文件夹和文本文件怎么做

在磁盘D创建两个文件时,具体代码如下,程序是对着书上敲的,为啥会报错呢?
有无同行解答


import java.io.File;
import java.io.IOException;

public class Page166 {
    public static void main(String[] args) throws IOException {
        //磁盘下创建文件
        File file = new File("D:\\hello\\demo.txt");
        //如果存在这个文件就删除,否则就创建
        if (file.exists()) {
            file.delete();
        } else {
            System.out.println(file.createNewFile());
        }
        //在磁盘下创建一层目录,并且在目录下创建文件
        File fileDemo = new File("D:\\hello1\\demo.txt");
        //判断D:\hello1目录是否存在
        if (!(fileDemo.getParentFile().exists())) {
            fileDemo.getParentFile().mkdir();
        }
        //如果存在这个文件就删除,否则就创建
        if (fileDemo.exists()) {
            fileDemo.delete();
        } else {
            System.out.println(fileDemo.createNewFile());
        }
    }
}

运行结果:

img

Exception in thread "main" java.io.IOException: 系统找不到指定的路径。
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at com.javajichu.Page166.main(Page166.java:14)

Process finished with exit code 1

我的java文件是放在D盘的: D:\untitled\src\com\包名中的,当我把要创建的文件位置放在这个位置时,程序没有报错,如下:

import java.io.File;
import java.io.IOException;

public class Page166 {
    public static void main(String[] args) throws IOException {
        //磁盘下创建文件
        File file = new File("D:\\untitled1\\src\\com\\demo.txt");     //为本文件路径
        //如果存在这个文件就删除,否则就创建
        if (file.exists()) {
            file.delete();
        } else {
            System.out.println(file.createNewFile());
        }
        //在磁盘下创建一层目录,并且在目录下创建文件
        File fileDemo = new File("D:\\untitled1\\src\\com\\demo1.txt");    //为本文件路径
        //判断D:\hello1目录是否存在
        if (!(fileDemo.getParentFile().exists())) {
            fileDemo.getParentFile().mkdir();
        }
        //如果存在这个文件就删除,否则就创建
        if (fileDemo.exists()) {
            fileDemo.delete();
        } else {
            System.out.println(fileDemo.createNewFile());
        }
    }
}

img

但这里我去除了hello和hello1文件夹,不然就会报错,是不能创建文件夹吗?
当我要完成上面的那种形式时,该怎么修改代码?

File只能创建文件,创建目录要调用mkdir()方法。

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632