Java file bytes


 

Java file bytes

In this section, you will learn how to read bytes from a file.

In this section, you will learn how to read bytes from a file.

Java file bytes

In this section, you will learn how to read bytes from a file.

Description of code:

InputStream class is one of the most fundamental component of java.io.* package. You can see in the given code, we have used InputStream class along with the FileInputstream class to obtain the byte of data from the given file. The method read() of InputStream class has provide this utility and read the data from the file in sequential order till the end of the file.

InputSream: This is an abstract class which is the super class of all classes that represents an input stream of bytes.

FileInputStream: This class obtains input bytes from a file in a file system.

read()-  This is the method of InputStream class which reads the next byte of data from the input stream.

Here is the code:

import java.io.*;

public class FileBytes {
	public static void main(String[] args) throws Exception {
		File file = new File("C:/file.txt");
		InputStream in = new FileInputStream(file);
		int bytes;
		while ((bytes = in.read()) != -1) {
			System.out.println(bytes);
		}
		in.close();
	}
}

Ads