简体   繁体   English

java'File'对象未创建目录和文件

[英]java 'File' Object not making the directory and file

I was trying to make a directory and file using java with File object as: 我试图使用带有File对象的java创建目录和文件:

import java.io.*;
class CreateFile{

    public static void main(String[] args) throws IOException{
        File f = new File("File/handling/file1.txt");
        if(!f.exists())
           f.createNewFile();
    }
}

but its showing error (see below) and unable to make it, the path and file name doesn't existed before execution. 但是它显示错误(请参阅下文)并且无法执行,执行前路径和文件名不存在。 I don't know where am I going wrong, someone please clarify whats the mistake and how to resolve it? 我不知道我要去哪里错了,请有人说明错误所在以及如何解决? It might be I need to know something about File object, so please do tell me... 可能是我需要了解一些有关File对象的信息,所以请告诉我...

See error: 看到错误:

Exception in thread "main" java.io.IOException: The system cannot find the path
specified

    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:947)
    at CreateFile.main(CreateFile.java:6)

The error is telling you that either there is no File directory relative to where you're running this, or there is but it doesn't have a handling subdirectory. 该错误告诉您,相对于您在其中运行此File而言,没有File目录,或者没有但没有handling子目录。 In this case, exists returns false and so you call createNewFile to try to create the file, but the directory in which you're trying to create it doesn't exist, and so it throws an exception. 在这种情况下, exists返回false ,因此您调用createNewFile尝试创建文件,但是要在其中创建文件的目录不存在,因此将引发异常。

You can use mkdirs to create the directories if necessary, like so: 如有必要,可以使用mkdirs创建目录,如下所示:

import java.io.*;
class CreateFile{

    public static void main(String[] args) throws IOException{
        File f = new File("File/handling/file1.txt");
        if(!f.exists()) {
           f.getParentFile().mkdirs(); // This is a no-op if it exists
           f.createNewFile();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM