Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
 
 
Search All Tutorials
  

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Java read file line by line - Java Tutorial

                         

Introduction

Lets understand some I/O streams that are used to perform reading and writing operation in a file. In the section of Java Tutorial you will learn how to write java program to read file line by line. 

Java supports the following I/O file streams.

  • FileInputstream
  • FileOutputStream 

FileInputstream:

This class is a subclass of Inputstream class that reads bytes from a specified file name . The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throws FileNotFoundException, if the specified file is not exist. You can use the constructor of this stream as:

FileInputstream(File filename);

FileOutputStream:

This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter class. You can use the constructor of this stream as:

FileOutputstream(File filename);

 DataInputStream:

This class is a type of FilterInputStream that allows you to read binary data of Java primitive data types in a portable way. In other words, the DataInputStream class is used to read binary Java primitive data types in a machine-independent way. An application uses a DataOutputStream to write data that can later be read by a DataInputStream. You can use the constructor of this stream as:

DataInputStream(FileOutputstream finp);

The following program demonstrate, how the contains are read from a file.

import java.io.*;

public class ReadFile{
    public static void main(String[] argsthrows IOException{
      File f;
    f=new File("myfile.txt");

      if(!f.exists()&& f.length()<0)
      System.out.println("The specified file is not exist");

      else{
         FileInputStream finp=new FileInputStream(f);
      byte b;
    do{
      b=(byte)finp.read();
      System.out.print((char)b);
    }
      while(b!=-1);
        finp.close();
        }
    }
  }


Output of the Program:

C:\nisha>javac ReadFile.java

C:\nisha>java ReadFile
This is a text file?
C:\nisha>

This program reads the bytes from file and display it to the user.

Download this Program

The another program  use DataInputStreams for reading textual input line by line with an appropriate BufferedReader.

import java.io.*;
class FileRead 
{
   public static void main(String args[])
  {
      try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Output of the Program:

C:\nisha>javac FileRead.java 

C:\nisha>java FileRead
this is a file

C:\nisha>

Download the code

                         

Facing Programming Problem?
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

5 comments so far (post your own) View All Comments Latest 10 Comments:

It is very fine the beginners.It is very useful to solve the specific problem.

Posted by SIVA on Friday, 05.16.08 @ 01:31am | #60093

Sir,
In this example we use readline instead of strline

Posted by Husnul on Saturday, 08.25.07 @ 09:57am | #24089

This will be very helpful to getting me started on Java.

Posted by Nat on Wednesday, 08.1.07 @ 23:40pm | #22450

It is very fine the beginners.It is very useful to solve the specific problem.

Posted by Rajeshwaran.N on Friday, 06.29.07 @ 16:17pm | #20377

Very Good. The code helped me alot.

Thanks to roseIndia. Thanks a lot.


Very Good.

Posted by Subbarao Anaparthi on Thursday, 03.1.07 @ 18:08pm | #10049

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Hot Web Programming Job

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.