Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用java创建文件(而不是文件夹)?_Java - Fatal编程技术网

如何用java创建文件(而不是文件夹)?

如何用java创建文件(而不是文件夹)?,java,Java,也许有点尴尬,但几个小时后我仍然无法用Java创建文件 File file = new File(dirName + "/" + fileName); try { // --> ** this statement gives an exception 'the system cannot find the path' file.createNewFile(); // --> ** this creates a folder also named a direc

也许有点尴尬,但几个小时后我仍然无法用Java创建文件

File file = new File(dirName + "/" + fileName);
try
{
    // --> ** this statement gives an exception 'the system cannot find the path'
    file.createNewFile();
    // --> ** this creates a folder also named a directory with the name fileName
    file.mkdirs();
    System.out.println("file != null");
    return file;
}
catch (Exception e)
{
    System.out.println(e.getMessage());
    return null;
}

这里缺少什么?

首先尝试创建父目录:

File file = new File(dirName + File.separator + fileName);
try {
    file.getParentFile().mkdirs();
    file.createNewFile();
    System.out.println("file != null");
    return file;
}
catch (Exception e)
{
    System.out.println(e.getMessage());
    return null;
}

谢谢,让人困惑的是,java似乎没有将文件与foldersHow区分开来,java应该这样做吗?什么是“a”,文件还是目录?为什么“foo.dat”应该是一个文件而不是一个目录?你必须告诉Java你想要什么。如果您告诉Java创建一个名为“index.html”的目录,它会很高兴地创建一个名为“index.html”的目录:)你的评论来自程序员的角度,我的困惑来自用户的角度,因为计算机用户区分文件夹和文件;java可以选择支持人类,例如使用文件类型枚举。许多文件系统不区分文件和文件夹。(文件夹就是文件)Java只是在镜像这种设计。@杰拉德:Java类型的“文件”只是文件系统对象的抽象。上述代码在任何JVM和任何操作系统上都同样适用。是否选择将给定文件对象视为文件或目录取决于您。如果您只是查询文件系统,并且需要知道现有文件系统对象是文件还是目录,那么应该调用其中一个布尔方法file.isDir()或file.isFile()。我总是尝试使用这些更具体的方法之一,而不是File.exists()。
String dirName="c:\\dir1\\dir2";
    String fileName="fileName.txt";
    File file = new File(dirName + "/" + fileName);
    try {
        new File(dirName).mkdirs();   // directory created here
        file.createNewFile();  // file created here
        System.out.println("file != null");
        return file;
    }catch(Exception e)
         {
            System.out.println(e.getMessage());
            return null;
         }