-
Notifications
You must be signed in to change notification settings - Fork 8
How to read file in Java – DataInputStream
Ramesh Fadatare edited this page Jul 18, 2018
·
4 revisions
In this example, we will DataInputStream class to read file. A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
The readLine() from the type DataInputStream is deprecated. Sun officially announced this method can not convert property from bytes to characters. It’s advised to use BufferedReader.
Let's read file character by character. If you want read file line by line then prefer BufferReader.
package com.javaguides.javaio.fileoperations.examples;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* This Java program demonstrates how to read file in Java – DataInputStream.
* @author javaguides.net
*/
public class DataInputStreamExample {
public static void main(String[] args) {
try(InputStream input = new FileInputStream("C:/sample.txt");
DataInputStream inst = new DataInputStream(input);){
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
https://docs.oracle.com/javase/8/docs/api/java/io/DataInputStream.html https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html