Reading A Text file In Java

Java makes available Reader classes to read character data from a number of different input sources. The BufferedReader class efficiently reads text from a file.

Heres a simple Junit test as an example.

package com.colwil.examples.text;

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

import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TextTest {

    File textFile = new File("textFile.csv");

    @Before
    public void before() throws IOException {
	FileUtils.writeStringToFile(textFile, "Hello and Welcome", "UTF-8", true);
    }

    @After
    public void after() {
	textFile.delete();
    }

    @Test
    public void textFileTest() throws Exception {

	String line = "";
	try (BufferedReader br = new BufferedReader(new FileReader(textFile))) {

	    while ((line = br.readLine()) != null) {
		System.out.println(line);
	    }

	} catch (IOException e) {
	    e.printStackTrace();
	}

    }
}

and heres the output we get

Hello and Welcome

Leave a Comment

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