File Handling || Reading and Writing data from a text file.

The simplest way to implement file handling is via using normal txt files. To achieve this we didn’t need any additional API. Reading and Writing data from a text file is very easy and simple process.

Reading Text Files
Reading Text Files

Steps to Reading the text files

  1. Locate the text file on the hard drive using FileReader class.
  2. Now load the file in memory using BufferedReader class.
  3. The next and last step is to reading data line by line using readLine() method of BufferedReader class.
  4. These content can be stored in a string and can be modified using other methods in Java.



Code Example
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author ashok.kumar
 *
 */
public class ReadingTxtFile {

	public static void main(String[] args) throws IOException {
		
		FileReader fr=new FileReader("inputs\\template.txt");
		BufferedReader bfr=new BufferedReader(fr);
		String currentLine=bfr.readLine();
		while(currentLine!=null)
		{
			System.out.println(currentLine);
			currentLine=bfr.readLine();
		}
	}
}

Related Links:

OOPs Concept:

OOPs Concept:

Java Question And Answer:


Steps to Writing data in a text file

  1. Locate the output location and file name using FileWriter class.
  2. Writing data in string format using write() method of FileWriter class.
  3. Once all data written on the file, we have to close the file using close() method of FileWriter class.
Code Example
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author ashok.kumar
 *
 */
public class WritingTxtFile {

	public static void main(String[] args) throws IOException {
		
		FileWriter fw=new FileWriter("output\\demo.txt");
		fw.write("This is demo file.");
		fw.close();
		System.out.println("Demo file created.");
	}
}



594total visits,1visits today

Leave a Reply

Your email address will not be published. Required fields are marked *