CODE
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
}
}
File exists.
This is a sample file
At 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
.
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.LINE F
remove the type casting and see the output. Integer values of range o to 255 are printed.