Reading from a character based file using the FileReader - Full Java Code
Reading from a character based file using the FileReader - Full Java Code
This article is part of a tutorial.
Tutorial Index page - Java File Read-Write
/** * $Id: ReadingAFile.java 97 2010-03-13 21:39:34Z oneyour $ * * This is an accompanying program for the article * <a href="http://www.1your.com/drupal/FullCodeReadingACharacterFileUsingFileReader " title="http://www.1your.com/drupal/FullCodeReadingACharacterFileUsingFileReader ">http://www.1your.com/drupal/FullCodeReadingACharacterFileUsingFileReader </a> * * Copyright (c) 2009 - 2010 <a href="http://www.1your.com" title="www.1your.com">www.1your.com</a>. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of <a href="http://www.1your.com" title="www.1your.com">www.1your.com</a> nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; /** * A simple program that demonstrates reading from file * using a File Reader. */ public class ReadingAFile { private String carriageReturn = "\n"; /** * The constructor that does all the work. * Reads the contents from a file and * prints it to the System.out stream */ public ReadingAFile(String filePath) { System.out.println("About to read a file"); // Read the file contents String fileContents = readFile(filePath); // Display the file contents outputFileContents(fileContents); } /** * Read the file specified by the filePath parameter using * a FileReader and a BufferedReader * * @param filePath * Path to the file * * @return * Contents of the file */ private String readFile(String filePath) { FileReader fileReader = null; BufferedReader bufferedReader = null; StringBuilder textFromFile = new StringBuilder(); try { fileReader = new FileReader(filePath); // throws FileNotFoundException bufferedReader = new BufferedReader(fileReader); // Read through the entire file String currentLineFromFile = bufferedReader.readLine(); // throws IOException while(currentLineFromFile != null) { // Add a carriage return (line break) to preserve the file formatting. textFromFile.append(carriageReturn + currentLineFromFile); currentLineFromFile = bufferedReader.readLine(); // throws IOException } return textFromFile.toString(); } catch (IOException ioException) { // Failed to read the file System.err.println("Problems reading from the file with the path '" + filePath + "'. Program will now exit"); ioException.printStackTrace(); } finally { // Good practice: Close the readers to free up any resources. try { if (bufferedReader != null) { bufferedReader.close(); } if (fileReader != null) { fileReader.close(); } } catch(IOException ioExceptionIgnore) { // Problems while closing the Readers. // Nothing much we can do and so we ignore. } } return textFromFile.toString(); } /** * Print the file contents to the System.out stream. * * @param fileContents * A String representing the file's contents. */ private void outputFileContents(String fileContents) { System.out.println("Successfully read the file contents which is printed below."); System.out.println(fileContents); } /** * Request and read input from the command line (System.in) * * @param inputMessage * The message to be displayed as a request to the user * * @return * The input from the command line * * @throws IOException * Any problems while reading the input */ public static String readCommandLineInput(String inputMessage) { System.out.println(inputMessage); Scanner scanner = new Scanner(System.in); String inputLine = scanner.nextLine(); return inputLine; } /** * This is the program's entry point */ public static void main(String[] args) { String sInstruction = "\n Enter the path of the file to read:\n"; // Get the XML file from the user String sFilePath = readCommandLineInput(sInstruction); // Check if the file exists i.e. the path is valid. File oFile = new File(sFilePath); if(!oFile.exists()) { System.out.print("File does not exist!"); } else { new ReadingAFile(sFilePath); } } }
Feedback or Questions?
We welcome feedback and questions and will try our best to attend to it as quickly as possible!
Please note that you would have to register before you can post in our forums and this is purely to guard us from the spam-bots. Be assured that we do not send spam mails and our website registration only takes minutes.
