Search code examples
javafilepathrelative-pathabsolute-path

How to set relatively address to write a file in JAVA?


When I write a string to a file, Java writes the file in project's root directory.

I want to write in a subdirectory. For example : project_root/my_subdir.

It is possible to write a file to an absolute path? It would be much better if my program was able to work on another system.


Solution

  • You can define the file as

    new File("project_root/my_subdir", newFileToCreate);
    

    or perhaps

    new File("project_root" + File.separator + "my_subdir", newFileToCreate);
    

    to keep this OS independent

    or you can use file to as the first parameter

    new File(new File("project_root" + File.separator + "my_subdir"), newFileToCreate);