Java's createNewFile() - will it also create directories?

后端 未结 6 852
野趣味
野趣味 2020-12-13 08:20

I\'ve got a conditional to check if a certain file exists before proceeding (./logs/error.log). If it isn\'t found I want to create it. However, will

         


        
6条回答
  •  情歌与酒
    2020-12-13 08:28

    Java 8 Style

    Path path = Paths.get("logs/error.log");
    Files.createDirectories(path.getParent());
    

    To write on file

    Files.write(path, "Log log".getBytes());
    

    To read

    System.out.println(Files.readAllLines(path));
    

    Full example

    public class CreateFolderAndWrite {
    
        public static void main(String[] args) {
            try {
                Path path = Paths.get("logs/error.log");
                Files.createDirectories(path.getParent());
    
                Files.write(path, "Log log".getBytes());
    
                System.out.println(Files.readAllLines(path));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题