- File Handling in Java
- Java
- Streams in Java
- 1. Input Stream:
- Creating an InputStream
- Methods of InputStream
- 2. Output Stream:
- Creating an OutputStream
- Methods of OutputStream
- 1. Byte Stream:
- 2. Character Stream:
- Java File Class Methods
- File operations in Java
- File Operations
- Releasing System Resources
- Catching Exceptions
- Varargs
- Atomic Operations
- Method Chaining
- What Is a Glob?
- Link Awareness
File Handling in Java
In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used by creating an object of the class and then specifying the name of the file.
Why File Handling is Required?
- File Handling is an integral part of any programming language as file handling enables us to store the output of any particular program in a file and allows us to perform certain operations on it.
- In simple words, file handling means reading and writing data to a file.
Java
In Java, the concept Stream is used in order to perform I/O operations on a file. So at first, let us get acquainted with a concept known as Stream in Java.
Streams in Java
- In Java, a sequence of data is known as a stream.
- This concept is used to perform I/O operations on a file.
- There are two types of streams :
1. Input Stream:
The Java InputStream class is the superclass of all input streams. The input stream is used to read data from numerous input devices like the keyboard, network, etc. InputStream is an abstract class, and because of this, it is not useful by itself. However, its subclasses are used to read data.
There are several subclasses of the InputStream class, which are as follows:
- AudioInputStream
- ByteArrayInputStream
- FileInputStream
- FilterInputStream
- StringBufferInputStream
- ObjectInputStream
Creating an InputStream
// Creating an InputStream InputStream obj = new FileInputStream();
Here, an input stream is created using FileInputStream.
Note: We can create an input stream from other subclasses as well as InputStream.
Methods of InputStream
S No. | Method | Description |
---|---|---|
1 | read() | Reads one byte of data from the input stream. |
2 | read(byte[] array)() | Reads byte from the stream and stores that byte in the specified array. |
3 | mark() | It marks the position in the input stream until the data has been read. |
4 | available() | Returns the number of bytes available in the input stream. |
5 | markSupported() | It checks if the mark() method and the reset() method is supported in the stream. |
6 | reset() | Returns the control to the point where the mark was set inside the stream. |
7 | skips() | Skips and removes a particular number of bytes from the input stream. |
8 | close() | Closes the input stream. |
2. Output Stream:
The output stream is used to write data to numerous output devices like the monitor, file, etc. OutputStream is an abstract superclass that represents an output stream. OutputStream is an abstract class and because of this, it is not useful by itself. However, its subclasses are used to write data.
There are several subclasses of the OutputStream class which are as follows:
- ByteArrayOutputStream
- FileOutputStream
- StringBufferOutputStream
- ObjectOutputStream
- DataOutputStream
- PrintStream
Creating an OutputStream
// Creating an OutputStream OutputStream obj = new FileOutputStream();
Here, an output stream is created using FileOutputStream.
Note: We can create an output stream from other subclasses as well as OutputStream.
Methods of OutputStream
S. No. | Method | Description |
---|---|---|
1. | write() | Writes the specified byte to the output stream. |
2. | write(byte[] array) | Writes the bytes which are inside a specific array to the output stream. |
3. | close() | Closes the output stream. |
4. | flush() | Forces to write all the data present in an output stream to the destination. |
Based on the data type, there are two types of streams :
1. Byte Stream:
This stream is used to read or write byte data. The byte stream is again subdivided into two types which are as follows:
- Byte Input Stream: Used to read byte data from different devices.
- Byte Output Stream: Used to write byte data to different devices.
2. Character Stream:
This stream is used to read or write character data. Character stream is again subdivided into 2 types which are as follows:
- Character Input Stream: Used to read character data from different devices.
- Character Output Stream: Used to write character data to different devices.
Owing to the fact that you know what a stream is, let’s polish up File Handling in Java by further understanding the various methods that are useful for performing operations on the files like creating, reading, and writing files.
Java File Class Methods
The following table depicts several File Class methods:
Method Name | Description | Return Type |
---|---|---|
canRead() | It tests whether the file is readable or not. | Boolean |
canWrite() | It tests whether the file is writable or not. | Boolean |
createNewFile() | It creates an empty file. | Boolean |
delete() | It deletes a file. | Boolean |
exists() | It tests whether the file exists or not. | Boolean |
length() | Returns the size of the file in bytes. | Long |
getName() | Returns the name of the file. | String |
list() | Returns an array of the files in the directory. | String[] |
mkdir() | Creates a new directory. | Boolean |
getAbsolutePath() | Returns the absolute pathname of the file. | String |
Let us now get acquainted with the various file operations in Java.
File operations in Java
The following are the several operations that can be performed on a file in Java :
Now let us study each of the above operations in detail.
1. Create a File
- In order to create a file in Java, you can use the createNewFile() method.
- If the file is successfully created, it will return a Boolean value true and false if the file already exists.
Following is a demonstration of how to create a file in Java :
File Operations
The Files class is the other primary entrypoint of the java.nio.file package. This class offers a rich set of static methods for reading, writing, and manipulating files and directories. The Files methods work on instances of Path objects. Before proceeding to the remaining sections, you should familiarize yourself with the following common concepts:
Releasing System Resources
Many of the resources that are used in this API, such as streams or channels, implement or extend the java.io.Closeable interface. A requirement of a Closeable resource is that the close method must be invoked to release the resource when no longer required. Neglecting to close a resource can have a negative implication on an application’s performance. The try- with-resources statement, described in the next section, handles this step for you.
Catching Exceptions
With file I/O, unexpected conditions are a fact of life: a file exists (or doesn’t exist) when expected, the program doesn’t have access to the file system, the default file system implementation does not support a particular function, and so on. Numerous errors can be encountered.
All methods that access the file system can throw an IOException . It is best practice to catch these exceptions by embedding these methods into a try- with-resources statement, introduced in the Java SE 7 release. The try- with-resources statement has the advantage that the compiler automatically generates the code to close the resource(s) when no longer required. The following code shows how this might look:
Charset charset = Charset.forName(«US-ASCII»); String s = . ; try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) < writer.write(s, 0, s.length()); >catch (IOException x)
Alternatively, you can embed the file I/O methods in a try block and then catch any exceptions in a catch block. If your code has opened any streams or channels, you should close them in a finally block. The previous example would look something like the following using the try-catch-finally approach:
Charset charset = Charset.forName(«US-ASCII»); String s = . ; BufferedWriter writer = null; try < writer = Files.newBufferedWriter(file, charset); writer.write(s, 0, s.length()); >catch (IOException x) < System.err.format("IOException: %s%n", x); >finally
In addition to IOException , many specific exceptions extend FileSystemException . This class has some useful methods that return the file involved ( getFile ), the detailed message string ( getMessage ), the reason why the file system operation failed ( getReason ), and the «other» file involved, if any ( getOtherFile ).
The following code snippet shows how the getFile method might be used:
try (. ) < . >catch (NoSuchFileException x)
For purposes of clarity, the file I/O examples in this lesson may not show exception handling, but your code should always include it.
Varargs
Several Files methods accept an arbitrary number of arguments when flags are specified. For example, in the following method signature, the ellipses notation after the CopyOption argument indicates that the method accepts a variable number of arguments, or varargs, as they are typically called:
Path Files.move(Path, Path, CopyOption. )
When a method accepts a varargs argument, you can pass it a comma-separated list of values or an array ( CopyOption[] ) of values.
In the move example, the method can be invoked as follows:
import static java.nio.file.StandardCopyOption.*; Path source = . ; Path target = . ; Files.move(source, target, REPLACE_EXISTING, ATOMIC_MOVE);
For more information about varargs syntax, see Arbitrary Number of Arguments.
Atomic Operations
Several Files methods, such as move , can perform certain operations atomically in some file systems.
An atomic file operation is an operation that cannot be interrupted or «partially» performed. Either the entire operation is performed or the operation fails. This is important when you have multiple processes operating on the same area of the file system, and you need to guarantee that each process accesses a complete file.
Method Chaining
Many of the file I/O methods support the concept of method chaining.
You first invoke a method that returns an object. You then immediately invoke a method on that object, which returns yet another object, and so on. Many of the I/O examples use the following technique:
String value = Charset.defaultCharset().decode(buf).toString(); UserPrincipal group = file.getFileSystem().getUserPrincipalLookupService(). lookupPrincipalByName("me");
This technique produces compact code and enables you to avoid declaring temporary variables that you don’t need.
What Is a Glob?
Two methods in the Files class accept a glob argument, but what is a glob?
You can use glob syntax to specify pattern-matching behavior.
A glob pattern is specified as a string and is matched against other strings, such as directory or file names. Glob syntax follows several simple rules:
- An asterisk, * , matches any number of characters (including none).
- Two asterisks, ** , works like * but crosses directory boundaries. This syntax is generally used for matching complete paths.
- A question mark, ? , matches exactly one character.
- Braces specify a collection of subpatterns. For example:
- matches «sun», «moon», or «stars».
- matches all strings beginning with «temp» or «tmp».
- [aeiou] matches any lowercase vowel.
- 6 matches any digit.
- [A-Z] matches any uppercase letter.
- [a-z,A-Z] matches any uppercase or lowercase letter.
Here are some examples of glob syntax:
- *.html – Matches all strings that end in .html
- . – Matches all strings with exactly three letters or digits
- *3* – Matches all strings containing a numeric value
- *. – Matches any string ending with .htm, .html or .pdf
- a?*.java – Matches any string beginning with a , followed by at least one letter or digit, and ending with .java
- – Matches any string beginning with foo or any string containing a numeric value
Note: If you are typing the glob pattern at the keyboard and it contains one of the special characters, you must put the pattern in quotes ( «*» ), use the backslash ( \* ), or use whatever escape mechanism is supported at the command line.
The glob syntax is powerful and easy to use. However, if it is not sufficient for your needs, you can also use a regular expression. For more information, see the Regular Expressions lesson.
For more information about the glob syntax, see the API specification for the getPathMatcher method in the FileSystem class.
Link Awareness
The Files class is «link aware.» Every Files method either detects what to do when a symbolic link is encountered, or it provides an option enabling you to configure the behavior when a symbolic link is encountered.