Java Tutorial
FileInputStream(String fileName) throws FileNotFoundExceptionhere fileName specifies the name of the file that we want to read in java program.
void close() throws IOExceptionTo read a file, read method is available in InputStream object.
int read() throws IOException
//Java code to read from file using FileInputStream class import java.io.*; class FileReadTest { public static void main(String args[]) throws IOException { FileInputStream fin; try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException ex) { System.out.println("File is not found: "+ args[0] + ", error: " + ex.toString()); return; } catch(ArrayIndexOutOfBoundsException ex) { System.out.println("Error: "+ ex.toString()); return; } int byteval; // Reading file content and prints in console output. while(true) { byteval = fin.read(); //stops loop when reading value -1 which is the end of file character. if(byteval == -1) break; System.out.print((char) byteval); } fin.close(); } }Output:
$ javac FileReadTest.java $ java FileReadTest input.txt # Reading Input for java program -------------------------------- Reading line1 Reading line2 Reading line3 -------------------------------
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page