Advertisement
FileInputStream(File file) |
---|
This constructor creates a FileInputStream object to read a file specified by the File object, which is passed to this constructor as a parameter. Example -
|
FileInputStream(String path) |
---|
This constructor creates a FileInputStream to read a file which is accessed by the path mentioned in the parameters of this constructor.
Example -
|
Methods | Description |
---|---|
available() | This method gives the remaining number of bytes available to read from this input stream. |
read() | This method reads one byte from this input stream. |
read(byte[] b) | This method reads a whole byte array from this input stream. |
close() | This method closes this input stream and also frees any resources connected with this input stream. |
World peace is extremely important.
//Java - Program to read one byte at a time through an existing file using FileInputStream.
import java.io.*;
class A
{
public static void main(String...ar)
{
try
{
FileInputStream fin= new FileInputStream("D:\\TextBook.txt");
int c;
//Reading one byte out of a file
while( (c=fin.read()) !=-1)
{
//casting byte to char for displaying on the screen
System.out.print((char)c);
}
fin.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
World peace is extremely important
Advertisement
//Java - Program to read a byte array out of an existing file using FileInputStream.
import java.io.*;
class A
{
public static void main(String...ar)
{
try
{
FileInputStream fin= new FileInputStream("D:\\TextBook.txt");
int num= fin.available();
System.out.println("Number of bytes available to read =" + num);
byte b[]= new byte[num];
int c;
//read() method stops reading from file when EOF is reached i.e. -1
if((c=fin.read(b))!=-1)
System.out.println("Number of bytes read = " +c);
String s= new String(b);
System.out.println(s);
fin.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Number of bytes available to read =34
Number of bytes read = 34
World peace is extremely important
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement