How to read file in java


 

How to read file in java

Java provides IO package to perform reading and writing operations with a file. In this section you will learn how to read a text file line by line in java.

Java provides IO package to perform reading and writing operations with a file. In this section you will learn how to read a text file line by line in java.

How to read file in java

Java provides IO package to perform reading and writing operations with a file. In this section you will learn how to read a text file line by line  in java.

FileInputStream- This class reads bytes from the given file name.

read()-The read() method of FileInputStream class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached.

StringBuffer- This class is used to store character strings that will be changed.

append()-The append() of StringBuffer class appends or adds the string representation of the char argument to this sequence.

Here is the code:

import java.io.*;

public class FileRead {
  public static void main(String[] args) {
    File file = new File("C:/file.txt");
    int ch;
    StringBuffer strContent = new StringBuffer("");
    FileInputStream fin = null;
    try {
      fin = new FileInputStream(file);
      while ((ch = fin.read()) != -1)
        strContent.append((charch);
      fin.close();
    catch (Exception e) {
      System.out.println(e);
    }
    System.out.println(strContent.toString());
  }
}

Here is the video tutorial of: "Ways to read file in Java?"

Another way of reading a file:

The another program  use DataInputStream for reading text file line by line with a BufferedReader. 

DataInputStream-This class read binary primitive data types in a machine-independent way. 

BufferedReader-This class read the text from a file line by line with it's readLine() method.

Here is the code:

import java.io.*;

class FileRead {
  public static void main(String args[]) {
    try {
      FileInputStream fstream = new FileInputStream("C:/file.txt");
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String str;
      while ((str = br.readLine()) != null) {
        System.out.println(str);
      }
      in.close();
    catch (Exception e) {
      System.err.println(e);
    }
  }
}

Ads