Share on Google+Share on Google+

Java read file

Ads
There are many ways to read a file in Java. DataInputStream class is used to read text File line by line. BufferedReader is also used to read a file in Java when the file in huge. It is wrapped around FileReader. Java supports reading from a Binary file using InputStream.

There are many ways to read a file in Java. DataInputStream class is used to read text File line by line. BufferedReader is also used to read a file in Java when the file in huge. It is wrapped around FileReader. Java supports reading from a Binary file using InputStream.

Close() method must be called every time.

Class DataInputStream

DataInputStream reads data types from input stream like FileInputStream. DataInputStream is not safe while accessing multithreads. FileInputStream is used for reading streams of raw bytes.

BufferedReader

BufferedReader class read text from a character-input stream rather than read one character, arrays, and lines at a time.

Using BufferedReader makes works faster as it reads a larger block rather than reading one character at a time.

Buffer size may be specified. BufferedReader must be wrapped around read() like such as FileReaders, InputStreamReaders and StringBuilder.

BufferedReader br = new BufferedReader(new InputStreamReader(in));

readline() is used to read the next line.

Example of Java Read File:

package FileHandling;

import java.io.BufferedReader;
import java.io.DataInputStream;

import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileReadTest {
	public static void main(String[] args) {

		try {

			FileInputStream fileInputStream = new FileInputStream("C:/file.txt");
			DataInputStream in = new DataInputStream(fileInputStream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String string;
			while ((string = br.readLine()) != null) {
				System.out.println(string);
			}
			in.close();
		} catch (Exception e) {
			System.err.println(e);
		}
	}
}

Advertisements

Ads

Posted on: April 30, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

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.

Discuss: Java read file  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

Advertisement