Reading a file using FileInputStream

Reading a file using FileInputStream

To read a file using FileInputStream in Java, follow these steps:

  1. Import the necessary packages:
import java.io.FileInputStream;
import java.io.IOException;

2. Create a FileInputStream object for the file you want to read:

FileInputStream fis = new FileInputStream("filename.txt");

3. Create a buffer array to store the data you read from the file:

byte[] buffer = new byte[1024];

4. Use the read method of the FileInputStream class to read data from the file into the buffer:

int bytesRead = fis.read(buffer);

The read method returns the number of bytes read from the file, or -1 if the end of the file has been reached.

5. Use the data you have read from the file, for example by converting it to a string:

String fileData = new String(buffer, 0, bytesRead);

6. Close the FileInputStream object to release any system resources it is holding:

fis.close();

Here is an example that reads the contents of a file and prints them to the console:

package ebhor.io;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStreamClass {

    public static void main(String[] args) {
        FileInputStream fis = null;
        int data;
        try {
            fis = new FileInputStream("D://first.txt");

            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (FileNotFoundException ex) {
            System.out.println("FileNotFoundException " + ex);
        } catch (IOException ex) {
            System.out.println("IOException " + ex);
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (Exception ex) {
                System.out.println("Exception " + ex);
            }
        }
    }
}