How to Read a File Using Java,Java Code to Read a File


How to Read a File Using Java,Java Code to Read a File,You can read the text file,xml file line by line. The below program will help you to know how to read file by using java code.

How to Read a File Using Java,Java Code to Read a File.
Java Code :
import java.io.*;
public class ReadMyFile {
public static void main(String[] args) {
// Give the path of the file
File file = new File("C:\\MyFolder\\MyFile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);

//BufferedInputStream will read the file content fastly.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

// when dis.available() returns 0 (No more line is there to read in dis.available() .
while (dis.available() != 0) {

// the below line will read the content from the file and will print in console.
System.out.println(dis.readLine());
}
// disconnect all the resources after using them.
fis.close();
bis.close();
dis.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

Output:
Hi,
This is the test file to read text file.


Attachments

  • MyFile (41295-18138-MyFile.txt)
  • Comments

    Author: Arthanari18 Nov 2010 Member Level: Bronze   Points : 1

    Before run this program you create one folder called MyFolder under your system C drive and download the MyFile.txt copy it into MyFolder and run it.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: