Whats in this post?
- Background and Explanation of the code
To copy code: Click “View Source” on the right of this code snippet.
Output, Background and Explanation of the code
Let us understand some I/O streams that are used to perform reading and writing operation in a file. In the section of Java Tutorial you will learn how to write java program to read file line by line.
Java supports the following I/O file streams.
This class is a subclass of Inputstream class that reads bytes from a specified file name. The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throws FileNotFoundException, if the specified file is not exist. You can use the constructor of this stream as:
This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter class. You can use the constructor of this stream as:
This example shows how to copy a binary file using Java FileInputStream and FileOutputStream classes. If you want to copy text file use FileReader and FileWriter classes instead of FileInputStream and FileOutputStream classes.