Create a File in Java
Overview
File class in Java is an abstract representation of file and directory path names. It contains variables and methods required for the creation, reading, updating, and deletion of files and directories. File, Files, and FileOutputStream are the classes that provide methods to create a file(s) or directory(s) in java. These classes provide necessary methods for working with path names, file names, creating a new file(s) and directory(s), etc. File and FileOutputStream class belong to java's io package, whereas Files class belongs to java's nio package.
Introduction
Imagine you have written a java program that fetches data from some remote server, but you cannot read the data instantly and decide that you want to read that data at some other suitable time. So basically you want your java program to store that data as soon as it fetches onto your hard disk. How will you store data on a physical storage device like a hard disk from your Java program?
File class in Java is used whenever a user wants to store new data, read and/or modify old data, append new data, create new folders, etc on to some storage device. It is a concrete class which provides methods for creating, reading, modifying, and deleting files and folders.
"There are mainly three ways of creating a file through code in Java using JDK libraries:
- Using the createFile() method of the Files class present in the java.nio package.
- Using the createNewFile() method of the File class present in the java.io package.
- Using the FileOutputStream(String fileName, boolean append) constructor of the FileOutputStream class present in the java.io package.
where, io stands for input-output and, nio stands for non-blocking input-output.
File(s) can also be created in Java using some external libraries like Google Guava, and Apache Commons IO library.
Ways to Create File in Java
Files.createFile() Method
"The Files.createFile() method is used to create a new file. It is a method of the Files class, which belongs to the java.nio.file package. This method creates a new file if a file with the same name does not already exist. However, if the file already exists, an exception named FileAlreadyExistsException is thrown.
Files class belongs to java.nio package.
Interesting Fact:
java.nio package is buffer oriented.
Syntax:
public static Path createFile(Path path, FileAttribute<?>... attributes) throws IOException
Creates a new and empty file if the file does not already exist, otherwise, it throws an exception if the file already exists. The attributes parameter is optional file attributes to set atomically when creating the file. Each attribute is identified using its name. If more than one attribute of the same name is present in the array then all occurrences will be ignored except the last occurrence.
Parameters:
path - path to the file. attributes - an optional list of file attributes to set automically during file creation. A FileAttribute is an object that encapsulates the value of a file attribute that can be set atomically like File permissions can be set in a file attribute. e.g,
Returns:
The created file
Throws:
UnsupportedOperationException - if the FileAttribute array contains an attribute that cannot be set atomically when creating the file
FileAlreadyExistsException - if a file of that name already exists (optional specific exception)
IOException - if an I/O error occurs or the parent directory does not exist
SecurityException - In the case of the default provider, and a security manager is installed, the checkWrite method is invoked to check write access to the new file.
Example:
Output(s):
Explanation:
As we already discussed that Files.createFile() method requires a Path class object as an argument, so we have created a path object of Path class, for the file path given as "newFile.txt". As we have not used anything before newFile.txt, this means that the compiler will look for the file in the current working directory itself, where the current program is saved.
The file gets created when there does not exist a file previously, but if the file already exists in the directory, then a FileAlreadyExistsException will be thrown, which is handled by a print statement, to notify the user.
"The createNewFile() method belongs to the File class in Java's java.io package. It is used to create a new, empty file. The method does not accept any arguments. If the file does not already exist, it will be automatically created.
The File class is stream-oriented, which means it provides methods for reading or writing streams of bytes. However, the createNewFile() method itself does not perform any stream-oriented operations. It simply creates an empty file on the file system.
When working with stream-oriented operations, such as reading bytes from a stream, you can read one or more bytes at a time, but they are not inherently cached anywhere. To enable flexibility in moving back and forth in the data read from a stream, you can cache the data in a buffer first. However, the caching process is not directly related to the createNewFile() method itself.
Interesting Fact:
java.io package is stream oriented.
Syntax:
public boolean createNewFile() throws IOException Atomically creates a new and empty file if and only if a file with the same name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
Parameters:
None
Returns:
true - if the file does not exist and was successfully created; false - if the file already exists;
Throws:
IOException - If an I/O error is occurred SecurityException - If a security manager exists and the method SecurityManager.checkWrite(java.lang.String) denies the write access to the file
Example:
Output(s):
Explanation:
Here, an object of the File class is created, which has the function createNewFile(). This function returns a value true if the file is created successfully, else it will return a false if the file already exists. Respective print statements are written for the user’s convenience, in order to get the actual status.
File.createNewFile() function also throws an IOException, which is handled using the try-catch block.
FileOutputStream() Method
A FileOutputStream is an output stream used for writing data to a File or FileDescriptor. It is part of Java's java.io package and provides support for file-related operations. The class offers different constructors to create instances for writing to files. When creating a new instance, if the file does not exist, a new file is created. However, if there are security restrictions or insufficient permissions, a FileNotFoundException is thrown.
Important Fact:
FileOutputStream is primarily designed for writing streams of raw bytes, such as image data. For writing streams of characters, it is recommended to use the FileWriter class.
Syntax:
- FileOutputStream(File file): Creates a file output stream to write to the file represented by the given File object.
- FileOutputStream(File file, boolean append): Creates a file output stream to write to the file represented by the given File object in append mode if append is set to true.
- FileOutputStream(FileDescriptor fdObj): Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.
- FileOutputStream(String fileName): Creates a file output stream to write to the file represented by the given fileName string.
- FileOutputStream(String fileName, boolean append): Creates a file output stream to write to the file represented by the given fileName string in append mode if append is set to true.
Example:
Output(s):
Explanation:
Here, we are creating a FileOutputStream class object using a file name and the append mode set to true, which means the new data will be added to the file after the end text. We have taken a sample text in the string, and after converting it to raw bytes, written it to the file output stream, and closed the stream at the end after all work is done. If the file does not exist, then a new file is created. If the file is not able to open due to security reasons, then FileNotFoundException is thrown which is handled using the try-catch block.
IO vs NIO Package
The provided comparison between the IO and NIO packages accurately highlights the key differences:
IO | NIO |
---|---|
Represents blocking Input/Output operations. | Represents non-blocking Input/Output operations. |
Stream-oriented: Read one or more bytes at a time from a stream. The processing of the data read is up to the developer. The bytes are not cached, limiting the ability to move back and forth within the data. | Buffer-oriented: Data is read into a buffer, allowing for more flexible manipulation. Data is cached in the buffer, enabling movement back and forth within the data during processing. |
Does not inherently provide the flexibility to move back and forth within the data read from a stream due to the lack of caching. | Provides flexibility to move back and forth within the data as it is cached in a buffer, allowing for efficient processing. |
Conclusion:
- There are 3 methods to create a file in Java: Using Files.createFile() method, Using File.createNewFile() method, and, Using FileOutputStream class Constructor
- Files class belong to java.nio package, whereas File and FileOutputStream classes belong to java's io package
- java's nio package is buffer-oriented and java's io package is stream-oriented.
- FileOutputStream is an output stream for writing data to a File or to a FileDescriptor.
- File.createNewFile() is stream-oriented and creates a new and empty file automatically if it does not yet exist.
- Files.createFile() is buffer-oriented and thus gives more flexibility to move back and forth in the data as the data is cached in the buffer first and processed afterward, as compared to stream-oriented methods.