public abstract class InputStream
extends Object
implements Closeable
Important Methods :
Let's create a sample file
fileOne
with the absolute path
E: JavaPrograms\FolderOne\fileOne.txt
and write into it
"This is a sample file". Now we will write a sample program on
InputStream
to read data from
fileOne
.
InputStreamDemo
import java.io.*;
class InputStreamDemo
{
public static void main(String[] args) throws IOException
{
File f = new File("E:JavaPrograms\\FolderOne\\fileOne.txt"); //LINE A
InputStream is = new FileInputStream(f); // LINE B
if(f.exists()) // LINE C
{
System.out.println("File exists.");
// LINE D
int i = 0;
// LINE E
while((i = is.read()) != -1)
{
System.out.print((char) i); // LINE F
}
}
else
System.out.println("File not found.");
is.close(); // LINE G
}
}
OUTPUTFile exists.
This is a sample file
DESCRIPTIONAt LINE A
we have given the path for file f
.
At LINE B
we have created an FileInputStream
object and passed file f
as parameter.
At LINE C
we are checking whether file f
exists or not.
At LINE D
we have created a variable i
to store the byte data from file f
. read
method always returns an integer of range 0 to 255
At LINE E
we are assigning the i
value to the byte value obtained from file f
through InputStream
.
At LINE F
we are type casting int
to char
in order to print characters.
At LINE G
we are closing the InputStream
.
THINGS TO TRY
- At
LINE E
change the data type of i
to byte
to see a compilation error. Since the return type of read
method is int
the compiler throws a compilation error.
RESET_CODE
- At
LINE F
remove the type casting and see the output. Integer values of range o to 255 are printed.
Rest of Methods :