Using FileInputStream to read files by stream

Home arrow Java Tutorials arrow Java Essentials arrow Using FileInputStream to read files by stream
Using FileInputStream to read files by stream Print E-mail
Contributed by Joe   
Saturday, 09 September 2006

java.io.FileInputStream is a concrete subclass of java.io.InputStream.,

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

FileInputStream( ) has three constructors

  • public FileInputStream(String fileName) throws IOException
  • public FileInputStream(File file) throws FileNotFoundException
  • public FileInputStream(FileDescriptor fdObj)

The first constructor uses a string containing the name of the file. The second constructor uses a java.io.File object. The third constructor uses a java.io.FileDescriptor object.

Example : reading a   file

To read a file, just pass the name of the file into the FileInputStream( ) constructor. Then use the read( ) method as normal. \

try {
  FileInputStream fis = new FileInputStream("date.txt");
  for (int n = fis.read(); n != -1; n = fis.read( )) {
    System.out.write(n);
  }
}
catch (IOException ex) {
  System.err.println(ex);
}

 Note: Filenames are platform-dependent, so hardcoded filenames should be avoided wherever possible

Last Updated ( Saturday, 09 September 2006 )

  home              contact us

 

©2006-2008 DeveloperZone.biz   All rights reserved     powered by Mambo Designed by Siteground