Contoh program kali ini ngejava.com akan membuat contoh program untuk membaca file menngunakan bufferedReader class.
kita akan menggunakan 2 methods dalam contoh program dibawah ini
- readLine() methods
- read() methods
sebelumnya buatlah 2 file dengan notepad untuk dibaca, saya membuat file "newfile.txt" dan "newfile_2.txt" yang berada di direktori "C:\\newfile.txt" dan C:\\newfile_2.txt, berikut contoh programnya
Nama file : read_File.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class read_File {
public static void main(String[] args) {
BufferedReader br = null;
BufferedReader br2 = null;
try{
br = new BufferedReader(new FileReader("C:\\newfile.txt"));
//One way of reading the file
System.out.println("Reading the file using readLine() method:");
String contentLine = br.readLine();
while (contentLine != null) {
System.out.println(contentLine);
contentLine = br.readLine();
}
br2 = new BufferedReader(new FileReader("C:\\newfile_2.txt"));
//Second way of reading the file
System.out.println("");
System.out.println("Reading the file using read() method:");
int num=0;
char ch;
while((num=br2.read()) != -1)
{
ch=(char)num;
System.out.print(ch);
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try {
if (br != null)
br.close();
if (br2 != null)
br2.close();
}
catch (IOException ioe)
{
System.out.println("Error in closing the BufferedReader");
}
}
}
}
Output
program dibuat menggunakan netbeans
selamat mencoba,semoga bermanfaat ...
No comments:
Post a Comment