Hello friends Today We discuss the concept of reading bytes from file using java codes. The reading bytes from file using java is done by using FileInputStream which make an object of text file in this the object of file is used to take input from text file from which we have to read byte.
This is done by using:
FileInputStream object=new FileInputStream(“filename.txt”);
In this filename.txt is the name of file which is taken as input by using FileInputStream.
Before we start to make program for reading bytes from file using java check these:-
1) Is jdk is installed on your pc if not then please install it first, to see how to install click here.
2) set path variable for java runtime environment(jre), click here to see how to set path.
If these conditions are ok?.
If yes then Now we start coding
JAVA CODES FOR READING BYTE FROM FILE:-
import java.io.*;
class byt{
public static void main(String args[]){
System.out.println(“*********No. of Bytes in an file*********”);
FileInputStream f= null; //used to make object of file.
try{
int ch;
f=new FileInputStream(“max.txt”);
if ((ch=f.read())!=-1) // here -1 shows end of file. { System.out.println(“No. of byte=”+ch); System.out.println((char)ch);
}
f.close();
}
catch(IOException e){
System.out.println(“Error in file handling are:”);
System.out.println(e);
}
}
}
After writing this code
1) save the file as byt.java .
2) open command prompt and go to file location where you save your java code by using cd command for example
cd e:\java\bin
3) After going to file location compile java code by using
Java command for example
javac byt.java
4) run the code by using java command for example
java byt
5) then output of code will come
Is your code is running?
Its eAsy.
EXPLANATION OF CODE:
1) FileInputStream is used for taking input file from which we have to read byte and FileInputStream makes an object of file
by using this object we can easily read byte from file or calculate total number of bytes in an file.
2) f.read() is used to read byte from file.
3) f.close() is used to close the file.
4) try , catch block are used to handling the exception occurred
in file handling.
OUTPUT:
Links for more help:
1) for more programming concepts click here .
2) for query click here.
Thanks for reading this post………