The java.io package contains almost all the classes you need to perform input and output (I/O) in Java. All these streams represent the source of input and the destination of output. Streams in the java.io package support various data types such as primitive data types, object characters, and more.
Handling File Input and Output (I/O) in Java
Java Streams
Streams in Java can be defined as a sequence of data. There are 2 types of Streams in Java, including:
- InputStream: InputStream is used to read data from a source.
- OutputStream: OutputStream is used to write data to a destination.
Java provides robust yet flexible I/O support related to files and networks. In this article, Mytour introduces only the basic features related to Streams and I/O.
Byte Stream in Java
Byte Stream in Java is used for handling input and output of bytes (8 bits). While there are several classes related to byte streams, the most frequently used classes include FileInputStream and FileOutputStream.
Below is an example using these classes to copy an input file to an output file:
Now you will have an input.txt file with the content:
This is a test for copying files.
The next step is to compile and execute the program, resulting in the creation of a file named output.txt with the same content as input.txt. Therefore, you put the code into the CopyFile.java file and perform the following steps:
$javac CopyFile.java
$java CopyFile
Character Stream in Java
Byte Stream in Java is used for handling input and output of bytes (8-bit), while Character stream in Java is used for handling input and output of 16-bit Unicode.
While there are many classes related to character streams, the most frequently used classes include FileReader and FileWriter. Although FileReader uses FileInputStream and FileWriter uses FileOutputStream, a key difference is that FileReader reads 2 bytes at a time, while FileWriter writes 2 bytes at once.
The example above can be rewritten to use these two classes to copy an input file (with Unicode characters) to an output file:
Now you will have an input.txt file with the content:
This is a test for copying files.
The next step is to compile and execute the program, resulting in the creation of a file named output.txt with the same content as input.txt. Therefore, put the code into the
$javac CopyFile.java
$java CopyFile
Standard Stream in Java
All programming languages provide standard I/O support, where user programs can take input from the keyboard and produce output on the computer screen.
If you are familiar with programming languages like C or C++, you must be aware of the three standard devices STDIN, STDOUT, and STDERR. Similarly, Java also provides 3 Standard Streams, including:
- Input Standardization: This standard is utilized for entering data into the user's program, typically using the keyboard as the standard input and represented as System.in.
- Output Standardization: Used to output data generated by the user's program, usually using the computer screen as the standard output and represented as System.out.
- Error Standardization: Employed to output error data produced by the program, with the computer screen serving as the standard error and represented as System.err.
Here is a simple program creating an InputStreamReader to read standard input stream until the user inputs the character 'q':
Save the code snippet above in the file ReadConsole.java, then try compiling and executing it as shown below. This program continues to read and output the same character until the user enters the 'q' character:
File Reading and Writing in Java
As mentioned earlier, a stream can be defined as a sequence of data. InputStream is used to read data from a source, and OutputStream is used to write data to a destination.
Below is the hierarchical structure of classes for handling input and output (I/O) streams:
The two most crucial streams are FileInputStream and FileOutputStream, which Mytour will elaborate on in the following section.
FileInputStream in Java
FileInputStream in Java is used for reading data from files. Objects can be created using the new keyword and various available constructor types.
Here is a constructor taking the file name as a string to create an input stream object for reading the file:
InputStream f = new FileInputStream('C:/java/hello');
Below is a constructor taking a file object to create an input stream object for reading files. First, create a file object using the File() method as shown below:
File f = new File('C:/java/hello');
InputStream f = new FileInputStream(f);
Once you have the InputStream object, below is a list of methods that can be used to read the stream or perform other operations on the stream:
Additionally, there are some other crucial input streams, including:
- ByteArrayInputStream
- DataInputStream
FileOutputStream in Java
FileOutputStream in Java is used to create a file and write data to that file. If the file does not exist, this stream will create a file before opening it for output.
Below are the 2 constructors used to create a FileOutputStream object:
- Constructor taking the file name as a string to create an output stream object for file writing:
OutputStream f = new FileOutputStream('C:/java/hello')
- Below is the constructor to take a file object to create an output stream object for writing files. First, create a file object using the File() method as shown below:
File f = new File('C:/java/hello');
OutputStream f = new FileOutputStream(f);
Once you have the OutputStream object, below is a list of methods that can be used to write to the stream or perform other operations on the stream:
Additionally, there are some other crucial output streams, including:
- ByteArrayOutputStream
- DataOutputStream
Example:
Here is an example of InputStream and OutputStream in Java:
The code snippet will create the test.txt file and write the given numbers in binary format. The output result will be similar on the stdout screen.
File Navigation and I/O (Input/Output) in Java
To understand the basic information about file navigation and I/O (Input/Output) in Java, here are some classes you need to know:
- Class File.
- Class FileReader.
- Class FileWriter.
Directories in Java
Directories in Java are Files that contain a list of other files and directories. You can use the File object to create directories and list the files available in the directory.
Create Directory in Java
There are 2 useful File methods that can be used to create directories:
- The method mkdir() creates a directory, returning True if successful and False if unsuccessful. Failure may occur because the specified path in the File object already exists, or the directory cannot be created because the entire path does not exist.
- The method mkdirs() creates both the directory and all its parent directories.
The example below creates the directory '/tmp/user/java/bin':
Compile and execute the code above to create '/tmp/user/java/bin'.
Note: Java automatically handles path separators on UNIX and Windows according to the respective conventions. If using the forward slash (/) on the Windows version of Java, the path will still be resolved accurately.
List Directories in Java
You can use the list() method provided by the File object to list all files and directories available in the directory as shown in the example below:
The example above will return the output results of directories and files available in the /tmp directory:
Above are some useful information related to File, input/output (I/O) handling in Java. Additionally, readers can refer to other articles on Mytour such as Using IF-Else Conditions in Java. Wishing you success.