Java - Create a file in a specific path

Create file (absolute path)

You can create a file object by passing the absolute path as an argument to File(). A file object is just a file pointing to that path, not actually creating a file.

If you pass a file object as an argument to Files.touch(), an actual file is created.

You can create a file in a specific path like this:

File tempDir = new File(System.getProperty("java.io.tmpdir"));

File file = new File(tempDir + "/text.txt");
System.out.println(file.toPath());
System.out.println(file.exists());

Files.touch(file);
System.out.println(file.exists());

Output:

/tmp/text.txt
false
true

You could directly enter the file path as an absolute path, but since the path may be different for each platform and user, I got the temp directory path temporarily available on the system with System.getProperty("java.io.tmpdir").

File.separator

Different OSes can use different delimiters such as / and \ to separate directories.

File.separator returns the separator used by the platform. If the code runs on various platforms such as Windows and Linux, you should use File.separator.

You can use File.separator to implement something like this:

File tempDir = new File(System.getProperty("java.io.tmpdir"));

File file = new File(tempDir + File.separator + "text.txt");
System.out.println(file.toPath());
System.out.println(file.exists());

Files.touch(file);
System.out.println(file.exists());

Output:

/tmp/text.txt
false
true

Create file (relative path)

If you create a file like File(tempDir, "text.txt"), text.txt file is created in the path of tempDir.

File tempDir = new File(System.getProperty("java.io.tmpdir"));

File file = new File(tempDir, "text.txt");
System.out.println(file.toPath());
System.out.println(file.exists());

Files.touch(file);
System.out.println(file.exists());

Output:

/tmp/text.txt
false
true
codechachaCopyright ©2019 codechacha