To create a new directory and a file within it using Java

后端 未结 2 544
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 18:46

I am trying to create a new directory and a file within this directory. Can any one tell me where am I going wrong?

I am using a Windows system and I want the direct

2条回答
  •  死守一世寂寞
    2020-12-16 19:13

    Do this in order to create a new directory inside your project, create a file and then write on it:

    public static void main(String[] args) {
        //System.getProperty returns absolute path
        File f = new File(System.getProperty("user.dir")+"/folder/file.txt");
        if(!f.getParentFile().exists()){
            f.getParentFile().mkdirs();
        }
        //Remove if clause if you want to overwrite file
        if(!f.exists()){
            try {
                f.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            //dir will change directory and specifies file name for writer
            File dir = new File(f.getParentFile(), f.getName());
            PrintWriter writer = new PrintWriter(dir);
            writer.print("writing anything...");
            writer.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } 
    
    }
    

提交回复
热议问题