Tuesday 26 May 2015

Filled Under:

How To Read And Write Txt File In Java

In this tutorial first we write a txt file using char array then read the same file using buffer reader.

CODE FOR WRITING TXT FILE:

import java.io.*;
public class filewrite
{
public static void main(String arg[]) throws Exception 
{
String source = "This is a text file";
char buffer[] = new char[source.length()];
source.getChars(0,source.length(),buffer,0);
FileWriter f1= new FileWriter("newread.txt");
for(int i=0;i<buffer.length;i++)
{
f1.write(buffer[i]);
}
f1.close();
}

}



There are so many situations when we need to read data from external file to do that we use File Reader and Buffer Reader as we done in this program to read text from external text file.

FileReader:

The file reader class creates a reader that can use to read the content from external file it has generally two constructor 
FileReader(String filepath)
FileReader(fileObj)

 NOTE:  In this program i have set complete path of file if you don't want to this than your txt file should be in bin folder.

CODING FOR READING TXT FILE:

import java.io.*;
public class fileread 
{
public static void main(String arg[])  throws Exception
{

FileReader fr = new FileReader("F:\\newread.txt");
BufferedReader br = new BufferedReader(fr);
String s;
while((s=br.readLine())!=null)
{
System.out.println(s);
}
fr.close();
}
}


OUTPUT:




0 comments:

Post a Comment