Java BufferedReader (jdk java.io.*)

What is BufferedReader ?
– Class BufferedReader is under java.io package of Java API.
– Its for reads text from a character-input stream, buffering characters so as to provide to the efficient reading of characters, arrays, and lines.

BufferedReader in = new BufferedReader(new FileReader(“foo.in“));

– will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file,
converted into characters, and then returned, which can be very inefficient.

— source article from oracle site : http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html

My Source Code To Try BufferedReader:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileRead {

 public static void main(String args[]) {
     // 1 read the contain from txt file.
    // 1.1. declare the object that use for read – BufferReader
BufferedReader readTheFile = null;
File fileWrite = null;
String inLine;
try {
readTheFile = new BufferedReader(new FileReader(“C:\\Users\\frank\\Desktop\\KERJA\\FileWriter\\fileread.txt“));
// 2. create a writer , write into new text file
fileWrite = new File (“C:\\Users\\frank\\Desktop\\KERJA\\FileWriter\\filewrite.txt“);
while ((inLine = readTheFile.readLine()) != null) {

// 2.1. check the file is exist or not, if not create the file.
if (!fileWrite.exists()) {
fileWrite.createNewFile();
System.out.println(“Create new FIle“);
}
// 2.2. write into filewrite.txt file
FileWriter fw = new FileWriter(fileWrite.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
System.out.println(inLine);
bw.write(inLine);
bw.close();
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (readTheFile != null){
readTheFile.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

 

OUTPUT :

Image

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s