How to create a file in Java

In this post we will learn how to create a file in Java using the standard Java NIO package. The examples below include how to create a file, creating a file with permissions and creating a temporary file.

How to create a file in Java:

Below is an example of how to create a file.

How to create a file in Java with specific permissions:

The following example shows how to create a file with owner read write permissions.

In the above example we set the file permissions usingĀ PosixFilePermission.OWNER_READ andĀ PosixFilePermission.OWNER_READ, this allows the owner of the file to have read and write permissions. For a full list of what permissions are available visit the API documentation which can be found in the reference section below.

How to create temporary file in Java:

The example below shows how to make a temporary file which will be deleted when the application ends. This approach is great for writing simple unit tests to complex end to end acceptance tests.

In summary we have demonstrated how to create a file in Java, how to set permissions and how to create a temporary file. You can find more information about the Files class in the API documentation, the link can be found in the references section below.

References:

  1. Java Files class API documentation
  2. Java PosixFilePermission class API documentation

Similar posts:

  1. How to read a file in Java

 

Leave a Reply