Create whole path automatically when writing to a new file

前端 未结 5 1061
野性不改
野性不改 2020-11-28 01:26

I want to write a new file with the FileWriter. I use it like this:

FileWriter newJsp = new FileWriter(\"C:\\\\user\\Desktop\\dir1\\dir2\\filename.txt\");


        
相关标签:
5条回答
  • 2020-11-28 01:56

    Since Java 1.7 you can use Files.createFile:

    Path pathToFile = Paths.get("/home/joe/foo/bar/myFile.txt");
    Files.createDirectories(pathToFile.getParent());
    Files.createFile(pathToFile);
    
    0 讨论(0)
  • 2020-11-28 01:56

    Use File.mkdirs().

    0 讨论(0)
  • 2020-11-28 01:57

    Something like:

    File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
    file.getParentFile().mkdirs();
    FileWriter writer = new FileWriter(file);
    
    0 讨论(0)
  • 2020-11-28 02:00

    Use File.mkdirs():

    File dir = new File("C:\\user\\Desktop\\dir1\\dir2");
    dir.mkdirs();
    File file = new File(dir, "filename.txt");
    FileWriter newJsp = new FileWriter(file);
    
    0 讨论(0)
  • 2020-11-28 02:05

    Use FileUtils to handle all these headaches.

    Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.

    openOutputStream(File file [, boolean append]) 
    
    0 讨论(0)
提交回复
热议问题