Friday May 04

Links

Books

User Menu

AddThis

AddThis Social Bookmark Button

How to read String from file

PDF Print E-mail
Thursday, 23 June 2011 18:35
AddThis Social Bookmark Button

The following example shows how to read string line by line of a text file using the default system encoding

How to read string from file using Java

String fileName = "inputFile.txt";
try {
    BufferedReader in = new BufferedReader(new FileReader(fileName));
    String line;
    while ((line = in.readLine()) != null) {
         logger.info(line);
    }
    in.close();
} catch (IOException e) {
    e.printStackTrace();
    //Handle exception
}
Read String from file remark

For logging configuration you can use the following log4j.properties file

Read a file line by line using Apache commons

Apache common IO offers a great utility class. LineIterator is an iterator over a the lines in a Reader


How to read a file line by line using Apache commons LineIterator

File file = new File("inputFile,txt");
LineIterator lineIterator = null;
try
{
    lineIterator = FileUtils.lineIterator(file);
    while(lineIterator.hasNext())
    {
        String line = lineIterator.next();
        // Process line
        logger.info (line);
    }
}
catch (IOException e)
{
    // Handle exception
}
finally
{
    LineIterator.closeQuietly(lineIterator);
}
Read String from file line by line example

LineIterator holds a reference to an open Reader. When you have finished with the iterator you should close the reader to free internal resources. This can be done by closing the reader directly, or by calling the close() or closeQuietly(LineIterator) method on the iterator.

Java IO file related subjects

Tags: java , apache , read , file , string , (ioexception , line , iterator , lineiterator , reader

Add comment


Security code
Refresh