Reading files in Java

I am going to show example which shows how to read a file in Java.
If you want to read some file you should start with FileInputStream. This class is a concrete subclass of InputStream. It provides an input stream connected to a particular file.
Example:

package tutorial;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.PrintStream;public class Main{ public static void main(String[] args){ FileInputStream fileInputStream = null; try{ String workingDirectory = System.getProperty("user.dir"); File fileDir = new File(workingDirectory,"src/tutorial"); File file = new File(fileDir,"Main.java"); fileInputStream = new FileInputStream(file); show(fileInputStream,System.out); } catch (IOException ex){ } finally{ try{if (fileInputStream != null){fileInputStream.close();}  } catch (IOException ex){}  }  System.out.println(); }  private static void show(FileInputStream fin,PrintStream out) throws IOException{ byte[] buffer = new byte[1024]; while (true){ int bytesRead = fin.read(buffer); if (bytesRead == -1){break; }  out.write(buffer,0,bytesRead); }  }}

Main method here is show(). It is very simple method. In general Java allows to work with all things very easy.

Share

No related posts.

Leave a Reply

  

  

  

You can use these HTML tags

<a href=""title=""><abbr title=""><acronym title=""><b><blockquote cite=""><cite><code><del datetime=""><em><i><q cite=""><strike><strong>

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna,tincidunt vitae molestie nec,molestie at mi. Nulla nulla lorem,suscipit in posuere in,interdum non magna.