Java Program to read data from a File using BYTE STREAM .
Objective
Write a Java program to read data from a file using Byte Streams.
Algorithm / Approach
- Prompt the user for a filename.
- Inside a
tryblock, initialize aFileInputStream. - Use
fin.read()to read the very first byte. It returns an integer (the ASCII value) or -1 if the file is empty. - Use a
while(i != -1)loop to continuously read bytes. - Inside the loop, cast the integer back to a character:
(char) iand print it. - Read the next byte at the end of the loop.
- Close the stream in the
finallyblock.
ReadFile.java
import java.util.*;
import java.io.*;
class ReadFile {
public static void main(String[] a)
{
System.out.print("Enter File Name: ");
Scanner s=new Scanner(System.in);
String file = s.nextLine();
FileInputStream fin;
try {
fin = new FileInputStream(file);
int i = fin.read();
while(i != -1) {
System.out.print((char)i);
i = fin.read();
}
}
catch(Exception e) {
System.out.println(e);
}
finally {
try{
fin.close();
}
catch(Exception e) {
System.out.print(e);
}
}
}
}
Expected Output
Enter File Name: Alok.txt Java Prowess is developed by Java, Android Trainer
Explanation of the Program
FileInputStreamis the counterpart toFileOutputStream. It reads raw bytes from a file one by one.- The
read()method is interesting: it doesn't return abyte; it returns anint. This is because a byte can be negative (in Java, bytes are signed, -128 to 127). The method needs a way to signal "End of File", which it does by returning -1. If it returned a byte, it couldn't distinguish between actual data and EOF. - By casting the returned integer to a
char, we convert the ASCII number back into a readable letter.
Complexity
Time Complexity
O(n) - Where n is the number of bytes in the file.
Space Complexity
O(1)