Java read file line by line - Java Tutorial
Lets 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 class is a type of FilterInputStream that allows you to read binary data of Java primitive data types in a portable way. In other words, the DataInputStream class is used to read binary Java primitive data types in a machine-independent way. An application uses a DataOutputStream to write data that can later be read by a DataInputStream. You can use the constructor of this stream as:
The following program demonstrate, how the contains are read from a file.
This program reads the bytes from file and display it to the user.
The another program use DataInputStreams for reading textual input line by line with an appropriate BufferedReader.
Output of the Program: