javafile-io

How to create a file in a directory in java?


If I want to create a file in C:/a/b/test.txt, can I do something like:

File f = new File("C:/a/b/test.txt");

Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.


Solution

  • The best way to do it is:

    String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
    // Use relative path for Unix systems
    File f = new File(path);
    
    f.getParentFile().mkdirs(); 
    f.createNewFile();