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

后端 未结 2 2105
花落未央
花落未央 2021-02-13 03:39

Perhaps somewhat embarassing, but after some hours I still cannot create a file in Java...

File file = new File(dirName + \"/\" + fileName);
try
{
    // -->          


        
相关标签:
2条回答
  • 2021-02-13 04:31
    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;
             }
    
    0 讨论(0)
  • 2021-02-13 04:34

    Try creating the parent dirs first:

    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;
    }
    
    0 讨论(0)
提交回复
热议问题