繁体   English   中英

如何在java(不是文件夹)中创建文件?

[英]How to create a file in java (not a folder) ?

也许有点尴尬,但几个小时后我仍然无法用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;
}
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;
         }

暂无
暂无

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

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