Home Java Beginners Java Read File Line by Line - Java Tutorial


Share on Google+Share on Google+

Java Read File Line by Line - Java Tutorial

In the tutorial I will explain you how to read a text file in Java line by line using the DataInputStream class of the Java API. The DataInputStream class used along with the BufferedReader for reading the file line by line. There are many benefits of reading the file line by line. If you read the file line by line then there will be less requirement of the memory.

Java Read File Line by Line - Example code of reading the text file in Java one line at a time


In the section of Java Tutorial you will learn how to write java program to read file line by line. We will use the DataInputStream class to Read text File Line by Line. Our example program is reading a text file (textfile.txt) one line at a time using the FileInputStream, DataInputStream and BufferedReader classes. This example of reading file is efficient and can be used to read large text files also.

Since this program is using the BufferedReader class to read the data from stream line by line, application is using very less memory and processing power. This program is effective in reading the huge text files which can range into many GB's in size.

Developers can also add the further processing logic to process the data line bye line. For example if there is requirement to process the large legacy data store in txt file then this program can be used very effectively.

You can also view the detailed tutorial of reading file line by line in Java programming language. This video tutorial will show you how you can write code, compile and then test the program.

Here is the video tutorial that explains you how to read a text file in Java one line at a time:

Video Tutorial of Java Read File Line By Line

Here is the simple Java code example which yet powerful that reads big text file one line at a time. In the following example code we have used the BufferedReader class which contains a method readLine() for reading one line of data one by one. You can easily run the example code on console or in IDE such Eclipse.

Here is the code of java program to Read text File Line by Line:

import java.io.*;
class FileRead 
 public static void main(String args[])

  // 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
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());

Download the code

If you run the above code, it will read "textfile.txt" file and will print the content of file on console one line at a time. Here you can add your code to process one line of data in each iteration. Such example is useful if you have to read big csv file and process the content of csv file line by line.


The Java I/O Package Examples is also very help full for anyone looking for file management examples in Java. Read the complete description of example program discussed above.

Here is the complete explanation of the program:

In this example code following Java classes and Interfaces are used:

Class DataInputStream

The DataInputStream is convenient class for reading the primitive data from the input stream. The data read by DataInputStream  is independent of the OS and machine. It can read the data from any input stream. The DataInputStream class can also read the data from output stream written by any other program. In our example discussed we are just reading the text file one line at a time. The DataInputStream  class must be used carefully as it not thread safe. Programmer must write own code for making the read thread safe in a multi threaded environment.

Implementing Data input streams and data output strings basically represents Unicode strings in such a format that can be regarded as a slight modification of UTF-8. UTF-8 or UCS Transformation Format-8-bit is a variable-width encoding which encodes each Unicode character in a set of 1 to 4 octets in which the number of octets is dependent upon the integer value assigned to the Unicode character. At present, UTF-8 is one of the major and dominant character encoding for the World Wide Web, which accounts for over half of all Web pages.

Important methods of DataInputStream class are:

  • read(byte[] b)
  • read(byte[] b, int off, int len)
  • readFully(byte[] b)
  • readDouble()

Constructor of DataInputStream class

Here are the constructor of DataInputStream class.

DataInputStream(InputStream in) - In this Constructor DataInputStream takes InputStream as constructor argument.

The BufferedReader class

The BufferedReader class is used to read data from the character input stream every efficiently. It can read data efficiently as characters, arrays and even lines. This class is very useful in reading the file line be line in Java very easily. You just have to create the object of BufferedReader class  by passing the the DataInputStream as constructor parameter and then use the methods of BufferedReader class  to read the desired data as characters, array or lines.

The BufferedReader class uses the default buffer size  of 8192 chars for reading the data into buffer. This buffer size is sufficient for general applications. But it is also possible to specify the buffer size as per requirement.

Here are the constructor of  BufferedReader  class:

BufferedReader(Reader in) - This constructor is using the default buffer size.

BufferedReader(Reader in, int sz) - Here second argument takes the buffer size as parameter.

If you don't use the BufferedReader class for reading the data line by line then the performance of the application will be very low. Because each request to the Reader internally sends the read request for underlying character or byte stream which is resource hungry and time consuming. So, developers should use the BufferedReader class to read the character stream.

Here is the example of using BufferedReader class:

 BufferedReader in
   = new BufferedReader(new FileReader("myfile.txt"));

If you don't use the buffering then the application performance will be slow. Since each time you calls the read() or readLine() method, the data will be read from the the file itself and convert into the characters. So to read the file line by line in Java you should always use the BufferedReader class.

Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.


If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 4, 2007

Related Tutorials

Ask Questions?    Discuss: Java Read File Line by Line - Java Tutorial   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
April 14, 2011

FileReader inFile = new FileReader(filename); BufferedReader bufRead = new BufferedReader(inFile); while ((line = bufRead.readLine()) != null) { }
taniya tripathi
April 16, 2011

diference between internet and intranet
May 26, 2011

Thanks a lot to Rose India
June 21, 2011

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()); } } } in the above program why we need to use the BufferedReader Class? can u explain?
June 24, 2011
I love you

I owe my first child to you. Without this I would've jumped off a five foot bridge.
June 24, 2011
How to Can I read previous line

Is there anyway to read previous line? for example I want to compare last line in file with certain value. how would I know that I've reached the last line?
June 26, 2011
Copy file to another with readline

String line = null; boolean firsttime = true; while ((line = input.readLine()) != null) { if (!firsttime) { contents.append(System.getProperty("line.separator")); firsttime = false; } mystringbuffer.append(line); }
July 12, 2011

DataInputStream in = new DataInputStream(fstream); Why do we need this? I tired code without it worked just as fine!
June 10, 2013
read and write a file

Any one pls help me... I want 2 read a file and write the "lines which are all contains the word error" into other file...... How can i fetch the particular lines which has the word error???
aba duncan
August 24, 2011

Please at run time there is no command to open and read the file. Can u help me
August 30, 2011

Hey, the code worked like a charm without a single change. Thanks a lot!
September 7, 2011
missing Strem.close()

you open 3 strems and close only 1.. not good!
September 22, 2011
Not so important

Hey post some effective code not so good dude
September 28, 2011
Main Program

Hai... I have some problem with my project.can you help me? I didn't know why it cann't run.the problem in browse data. please help me. here the codes. package Yaya; import gov.nasa.worldwind.WorldWindow; import defaProject.FFrame; import gov.nasa.worldwind.geom.Position; import java.util.Vector; public class GUI extends javax.swing.JFrame { WorldWindow wwd; BacaFile bf; MainProgram mp; SatuanPosisi sp; Posisi position1, position2, position3, positionP; FFrame fFrame; private Vector<String[]> data1, data2, data3; /** Creates new form GUI */ public GUI(FFrame fFrame) { initComponents(); mp = new MainProgram(); this.fFrame = fFrame; Lat1.setText("-0.70417");Lon1.setText("119.85528"); Lat2.setText("-0.6");Lon2.setText("119.7"); Lat3.setText("1.19139");Lon3.setText("121.4225"); LatP.setText("-0.87639");LonP.setText("119.83861"); this.setTitle("Penentuan Ketinggian Air Laut"); } private GUI() { throw new UnsupportedOperationException("Not yet implemented"); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); Lat1 = new javax.swing.JTextField(); Lat2 = new javax.swing.JTextField(); Lat3 = new javax.swing.JTextField(); Lon1 = new javax.swing.JTextField(); Lon2 = new javax.swing.JTextField(); Lon3 = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); LatP = new javax.swing.JTextField(); LonP = new javax.swing.JTextField(); button2 = new javax.swing.JButton(); button1 = new javax.swing.JButton(); nameFile2 = new javax.swing.JLabel(); nameFile1 = new javax.swing.JLabel(); Run = new javax.swing.JButton(); button3 = new javax.swing.JButton(); nameFile3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); jLabel1.setText("Lokasi 1 :"); jLabel2.setText("Lokasi 2 :"); jLabel3.setText("Lokasi 3 :"); jLabel4.setText("Latitude"); jLabel5.setText("Longitude"); jLabel6.setText("Lokasi P :"); LonP.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LonPActionPerformed(evt); } }); button2.setText("Browse"); button2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseLokasi(evt); } }); button1.setText("Browse"); button1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseLokasi(evt); } }); nameFile2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); nameFile2.setText(". . ."); nameFile2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); nameFile1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); nameFile1.setText(". . . "); nameFile1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); nameFile1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); Run.setText("Run"); Run.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Excecute(evt); } }); button3.setText("Browse"); button3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseLokasi(evt); } }); nameFile3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); nameFile3.setText(". . ."); nameFile3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(LatP, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(LonP)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Lat2) .addComponent(Lat1, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE) .addComponent(Lat3, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(10, 10, 10) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(Lon1) .addComponent(Lon3, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Lon2, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jLabel4) .addGap(80, 80, 80) .addComponent(jLabel5) .addGap(39, 39, 39))) .addGap(27, 27, 27) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(button3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(button2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Run, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(button1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)) .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(nameFile3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nameFile2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nameFile1, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)) .addGap(31, 31, 31)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(button1) .addComponent(nameFile1, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(15, 15, 15) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(button2) .addComponent(nameFile2, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Lat1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1) .addComponent(Lon1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Lon2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Lat2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Lat3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Lon3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(button3) .addComponent(nameFile3, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(14, 14, 14) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(LatP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(LonP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(Run))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jLabel6))) .addContainerGap(14, Short.MAX_VALUE)) ); button2.getAccessibleContext().setAccessibleParent(jPanel1); button1.getAccessibleContext().setAccessibleParent(jPanel1); Run.getAccessibleContext().setAccessibleParent(jPanel1); button3.getAccessibleContext().setAccessibleParent(jPanel1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void Excecute(java.awt.event.ActionEvent evt) { LeastSquare ls; positionP = sp.getData(3); double jarak1P = KonversiJarak.getJarak(position1.getLat(), positionP.getLat(), position1.getLon(), positionP.getLon()); double jarak2P = KonversiJarak.getJarak(position2.getLat(), positionP.getLat(), position2.getLon(), positionP.getLon()); double jarak3P = KonversiJarak.getJarak(position3.getLat(), positionP.getLat(), position3.getLon(), positionP.getLon()); double[] x = {jarak1P, jarak2P, jarak3P}; int numHari = data1.size(); int numJam = data1.elementAt(1).length; for (int i = 0; i < numHari; i++){ String[] temp1 = data1.get(i); String[] temp2 = data2.get(i); String[] temp3 = data3.get(i); for (int j = 0; j < numJam; i++){ double lev1 = Double.parseDouble(temp1[j]); double lev2 = Double.parseDouble(temp2[j]); double lev3 = Double.parseDouble(temp3[j]); double[] y = {lev1, lev2, lev3}; ls = new LeastSquare(x, y); double d = ls.getElevasi(0.0); } } } public void excecute() { mp.setDataP(Double.parseDouble(LatP.getText()),Double.parseDouble(LonP.getText())); mp.run(jPanel1); } private void browseLokasi(java.awt.event.ActionEvent evt) { bf = new BacaFile(); if (evt.getSource().equals(button1)){ data1 = bf.readElementByElement(); nameFile1.setText(bf.getNameFile()); position1 = sp.getData(1); fFrame.createIcon("stasiun", Position.fromDegrees(position1.getLat(), position1.getLon())); } else if (evt.getSource().equals(button2)){ data2 = bf.readElementByElement(); nameFile2.setText(bf.getNameFile()); position2 = sp.getData(2); fFrame.createIcon("stasiun", Position.fromDegrees(position2.getLat(), position2.getLon())); } else if (evt.getSource().equals(button3)){ data3 = bf.readElementByElement(); nameFile3.setText(bf.getNameFile()); position3 = sp.getData(3); fFrame.createIcon("stasiun", Position.fromDegrees(position3.getLat(), position3.getLon())); } } private void LonPActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new GUI().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JTextField Lat1; private javax.swing.JTextField Lat2; private javax.swing.JTextField Lat3; private javax.swing.JTextField LatP; private javax.swing.JTextField Lon1; private javax.swing.JTextField Lon2; private javax.swing.JTextField Lon3; private javax.swing.JTextField LonP; private javax.swing.JButton Run; private javax.swing.JButton button1; private javax.swing.JButton button2; private javax.swing.JButton button3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JLabel nameFile1; private javax.swing.JLabel nameFile2; private javax.swing.JLabel nameFile3; // End of variables declaration public Posisi getData(int index) { if (index==0) return Posisi.set(Double.parseDouble(LatP.getText()), Double.parseDouble(LonP.getText())); else if (index==1) return Posisi.set(Double.parseDouble(Lat1.getText()), Double.parseDouble(Lon1.getText())); else if (index==2) return Posisi.set(Double.parseDouble(Lat2.getText()), Double.parseDouble(Lon2.getText())); else if (index==3) return Posisi.set(Double.parseDouble(Lat3.getText()), Double.parseDouble(Lon3.getText())); return null; } }
February 21, 2013
This code

This was really helpful, thanks.
December 7, 2011
convaluted code isn't it?

Can't you just use: BufferedReader reader = new BufferedReader(new FileReader(filename)); to create the reader instead of all that guff?
Gaurav Chauhan
December 14, 2011

Thanks for this program. Its really knowledgeable.
Herock Hasan
December 14, 2011

Excellent article and so much helpful. Hope another helpful content will also get from this website
January 9, 2012
a question

will the above code, will be faster for reading a file whose size is greater than 200MB????
January 11, 2012

Pls send me the complete java tutorial and updatation.
January 14, 2012
File Reading

There is a much easier way to do this, and in one line: String line = ""; BufferedReader input = new BufferedReader(new FileReader("filename")); while ((line = input.readLine()) != null){ System.out.println(line); } //remember to close our streams or we run into issues! input.close();
January 19, 2012
Thank You

Great site. Always been helpful.
January 23, 2012
how to run this program

dear sir/madam, could you plz explain me the procedure to run this program Thanks vani
February 9, 2012
location of text file

i am using ntebeans on windows..... so where do i place my text file so that the object reads it?????
February 9, 2012

the above code is giving a error of not recognizing the "in" symbol in netbeans.................please help
February 11, 2012

very easy program filereader
February 18, 2012
can you help me

can you help me making my thesis... music streaming via bluetooth. thankz...
tyrone A. taborete
February 27, 2012
computer programming

search text file
Jemmy Adams
March 5, 2012
Read text file

Sirs; Please, send step by step how can I read a text file, I am a mechanical engineer, not a programmer or IT. Thanks Jemmy
March 22, 2012

Android system does not urasnetdnd PE format. so called windows exe files are in this format (PE stands for Portable Executable but it is not so portable after all!). likely Android executable frmat is ELF, a well-known widely used (among several systems) codes container .moreover, the code into windows executable files is for x86 processors (or for CLR, not JVM), and Android hardware for sure has no x86 processors and afaik no x86-opcode compatible processor too.so basically, it's nonsense converting an exe (specific format, specific system, specific machine code for specific processor, specific library bindings) into a file Android can read' (oh, as passive data you can transfer the exe to android as it is, but forget it can run it or even see that there's code inside! just data to it!) Was this answer helpful?
April 5, 2012

thanks a lot, just what i needed!
April 20, 2012

thanks for this,it helped a lot.
Gabriel Alejandro Matossian
May 9, 2012

I am very grateful, your article really helped me. Kind regards, Gabriel
Pratibha K
June 2, 2012
Deprecation error

for the line "while (( thisLine = br. readLine()) != null) { the dot after br is coming wrong in deprecation error. pls help me to solve this error.
June 13, 2012
A little error

You also need to add "outFile.close();" after "in.close();" Otherwise the last chunk gets chopped off and lost.
June 15, 2012

Thank you for code
June 25, 2012

Where do you put the file???
June 26, 2012

Hi Thank You very much ! I'm interested in Java programming. And I found Your example here. And I have downloaded it. I'm sure it will help me getting clever programming in Java. Yours sincerely Palle
iris potot
June 29, 2012
IT 16

give more examples!
July 5, 2012
nice tutorial

i tried it, no error :) i want to know, how to show the text file (*.txt) into form (textfield) and then import to mysql or another database
July 9, 2012
java using applet

need java using applet login coding
July 19, 2012
I got an error

hello, I try your code but I got this error: Error: textfile.txt (The system cannot find the file specified)
Bayan Al-Atrash
July 28, 2012

where must i save the file.txt??
Aishwarya Nathan
August 8, 2012

The code really really works :-)
August 29, 2012

thanks so much
Mohd Shoaib
September 2, 2012
Computer Science(Java)

Really helpful!!!!!!!!!!!!!
September 11, 2012

Hw to read a file frm a txt document & according to the no: of characters in the individual word we have to append the words in the document & display in the output screen.
pradip garala
September 21, 2012

Thanks for code...
pradip garala
October 3, 2012

October 27, 2012
its easy way

/*FileInputStream fstream = new FileInputStream("textfile.txt"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream);*/ //the above code can be avoided BufferedReader br = new BufferedReader(new FileReader("chits.txt"));
November 13, 2012

hi i have a file format like this 0274589654, 5 0245878968, 6 0278695455, -1 0245875258, .5 after reading from the file line by line. i want to read the first number into a variable and read the second number into another variable. need help urgently. thanks in advance for helping.
November 23, 2012
Alternative way

Try to be more concise... One can also try this: BufferedReader in = new BufferedReader(new FileReader("textfile.txt")); instead of using InputStreamReader, DataInputStream and FileInputStream. Hope it helps.
December 4, 2012

Hi, Can u plz tel me,How to run this program? show me in cmd prompt,how to run??? reply me
April 11, 2013
Another Way to New a BufferedReader

Instead of new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(new File(fileName))))); The following is more clear: new BufferedReader(new FileReader(filename));
Peter Lawrey
July 20, 2013
Can you not use DataInputStream to read text

DataInputStream is for reading binary not text. This bad example gets copied many, many times so can you remove DataInputStream here.
August 30, 2013
Good example of file reading

Hi, Thanks for posting such a nice tutorial. I was searching for the posts for reading a file which is very big in size, one line at a time. I also tried to read the complete file in memory but due to Java memory constraint it is not possible. So, I searched for the "Read file line by line in Java" on google and luckily found this tutorial. This post on reading file helped me a lot for solving my problem. After using the program here I am able to read big text file of around 3.5 GB without any error or memory issue. Program performance is also good. Thanks for such a nice post.
Gulam Haqqani
January 12, 2014

write a program in java that reads a text file which contains integer numbers separated by commas. Find the sum of even no's and sum of odd no's of each line. the output should be like this Line1: sume of even no's =--- & sum of odd no's = ---
Erick Sanvicente
February 16, 2014

hello, where should i put the file.txt so the program can read it?
May 8, 2014

Hi, In my project i read excel file this functionality working on my local host but i upload this project that time this functionality not working . what changes required please suggest me regards, Hitendra
tanveer islam
June 24, 2011
java file

how to create file
May 31, 2013

Hey it will read the data whatever u entered ok.But It didn't interact with File.So I am thinking it is not corrrect>Please forgive if there is wrong in my discussion
May 31, 2013

Sorry sorry I got thanq