Writing and Reading (Input/Output) From Files in Java.

In this article, I’m covering the common task of reading and writing files that contain text that are created with a simple text editor like Notepad or Wordpad. To read input from a disk file first construct a FileReader object with the name of the input file, then use the FileReader to construct a BufferedReader.

1
2
FileReader reader = new FileReader("input.txt");
BufferedReader br = new BufferedReader(reader);

This BufferedReader object can be use to read the file “input.txt”. You can use methods readLine() to read input from the file.
To write output to a file you construct a PrintWriter object with the given file name:

it is important that when you’re done writing data to the file you close the file with some clean up code

out.close();

If the output file already exist, it is emptied before the new data are written into it. If the file doesn’t exist, an empty file is created. Use print, println methods to send number, objects, and String to a PrintWriter:

1
2
3
out.println(20.40);
out.println(new Rectangle(5, 10, 15, 25));
out.println("Hello World!");

The print and println methods convert numbers to their decimal string representation and use the toString method to convert objects to strings.
Here’s some example code read from a file “products.txt” containing two peace of information product and price: products.txt
shirts 15.50
pants 29.99
socks 9.10
after reading each line we will parse the information separating the products from the price and parsing the price into a double which is necessary in order to do math calculation like the total price.

1
2
3
4
5
6
7
8
9
10
11
12
13
FileReader reader = new FileReader("products.txt");
BufferedReader br = new BufferedReader(reader);
String line = "";
int counter = 0;
//reading from file and parsing input
while((line = br.readLine()) != null)
{
System.out.println("Line "+counter++);
String productName = line.substring(0, line.indexOf(" "));
System.out.println(productName);
double productPrice = Double.parseDouble(line.substring(line.indexOf(" "), line.length()));
System.out.println(productPrice);
}

here’s the code to create a file and write data

1
2
3
4
5
6
7
8
Scanner myscan = new Scanner(System.in);
PrintWriter pw = new PrintWriter("products.txt");
String line = "";
int counter = 0;
System.out.println("Write to file");
String write = myscan.nextLine();
pw.write(write);
pw.close();

Remember to import the appropriate classes in order to use scanner, and Filereader objects.

import java.io.*;
import java.util.*;

Anytime you write or read input from a file you are expected to handle exceptions. In a method that is ready to handle a particular exception type, place the statement that can cause the exception inside a try block, and the handler inside a catch clause.

1
2
3
4
5
6
7
8
try
{
//your code here...
}
catch(Exception a)
{
System.out.println(a);
}
Share This!

Leave a Reply

Your email address will not be published.