mathajax

Java File Read Operation

The Java program explains how to read content from a file on the disk using the FileInputStream object having different read function operations.
The following basic file operation used in these program.

File Open
File open operation in Java is done while creating an instance/object to the FileInputStream by invoking constructor function with filepath a as argument.if the file is not found on specified file path, FileInutStream class throws an exception called FileNotFoundException.

File Read & close
After creating an instance of the FileInputStream class, they supports file read and close operation and also supports three ways of reading data from the file.They are, read a byte, read array of byte and read all bytes from the file.


The Java program is an example of reading content from a file on the disk in the manner of reading a single byte by one read operation. At the end of file, the read function returns -1.


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

public class FileRead {

 public static void main(String[] args) throws IOException 
 {      
  String fpath = "c://test.txt";
  FileInputStream  fis=new FileInputStream(fpath);   
  int b=0;
  while (  (b=fis.read()) !=  -1 ) 
  {
   System.out.print( (char) b );
  }   
  fis.close();     
 }

}


The Java program is an example of reading content from a file on the disk in the manner of reading array of byte by one read function invocation. The read function returns 0 at the end of file.



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

public class FileRead2 {

 public static void main(String[] args) throws IOException {
    
  
  String fpath = "c://test.txt";
  FileInputStream  fis=new FileInputStream(fpath);
  
  byte barray[]= new byte[128]; int rsz=0;
  
  while (  (rsz=fis.read(barray)) >  0 ) 
  {
     System.out.println( new String(barray,0,rsz) );
  }   
  fis.close();

 }

}


The Java program is an example of reading content from a file on the disk in the manner of reading all bytes by single read operation.



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

public class FileRead3 {

 public static void main(String[] args)  throws IOException {

      
   String fpath = "c://test.txt";
   FileInputStream  fis=new FileInputStream(fpath);
      
   
   int csz =fis.available();
   byte content[]=new byte[csz];
   
   fis.read(content); 
   fis.close();
   
      System.out.println(new String(content));

 }

}


Comments

Popular posts from this blog

Solving System of Linear Equations by Gauss Jordan Elimination

Matrix Forward and Back Substitution

Solve System of Linear Equations by LU Decompose

Matrix Determinant by Upper Triangular Matrix

Chebyshev distance between two points