Last Updated : 05 Jun, 2020
The
read()method of
DataInputStreamclass in Java is of two types:
public final int read(byte[] b) throws IOExceptionOverrides: This method overrides the read() method of FilterInputStream class. Parameters: This method accepts one parameter b which represents the byte array into which the data is to read. Return value: This method returns the number of bytes actually read. It returns -1 if the input stream is ended and no more data is available to read. Exceptions:
// Java program to illustrate
// DataInputStream read(byte[]) method
import java.io.*;
public class GFG {
public static void main(String[] args)
throws IOException
{
// Create input stream 'demo.txt'
// for reading containing
// text "GEEKSFORGEEKS"
FileInputStream inputStream
= new FileInputStream(
"c:/demo.txt");
// Convert inputStream to
// DataInputStream
DataInputStream dataInputStr
= new DataInputStream(
inputStream);
// Count the total bytes
// form the input stream
int count = inputStream.available();
// Create byte array
byte[] b = new byte[count];
// Read data into byte array
int bytes = dataInputStr.read(b);
// Print number of bytes
// actually read
System.out.println(bytes);
for (byte by : b) {
// Print the character
System.out.print((char)by);
}
}
}
Input: Output: public final int read(byte[] b, int offset, int length) throws IOExceptionOverrides: This method overrides the read() method of FilterInputStream class. Parameters: This method accepts three parameters:
// Java program to illustrate
// DataInputStream read(byte[], int, int) method
import java.io.*;
public class GFG {
public static void main(String[] args)
throws IOException
{
// Create input stream 'demo.txt'
// for reading containing
// text "GEEKSFORGEEKS"
FileInputStream inputStream
= new FileInputStream(
"c:/demo.txt");
// Convert inputStream to
// DataInputStream
DataInputStream dataInputStr
= new DataInputStream(
inputStream);
// Count the total bytes
// form the input stream
int count = inputStream.available();
// Create byte array
byte[] b = new byte[count];
// Read data into byte array
int bytes = dataInputStr.read(b, 4, 5);
// Print number of bytes
// actually read
System.out.println(bytes);
for (byte by : b) {
// Print the character
System.out.print((char)by);
}
}
}
Input: Output: 1.
https://docs.oracle.com/javase/10/docs/api/java/io/DataInputStream.html#read(byte%5B%5D)2.
https://docs.oracle.com/javase/10/docs/api/java/io/DataInputStream.html#read(byte%5B%5D, int, int)RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4