Read multiple character based files in a directory - Java Full Code
Read multiple character based files in a directory - Java Full Code
This article is part of a tutorial.
Tutorial Index page - Java File Read-Write
/** * $Id: ReadMultipleFilesFromADirectory.java 104 2010-04-05 01:23:24Z oneyour $ * * This is an accompanying program for the article * <a href="http://www.1your.com/drupal/FullCodeReadMultipleCharacterFilesInDirectory " title="http://www.1your.com/drupal/FullCodeReadMultipleCharacterFilesInDirectory ">http://www.1your.com/drupal/FullCodeReadMultipleCharacterFilesInDirectory </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; /** * A simple program that reads all files with in a specified directory. * * Note that this class makes use of the class ReadingAFile * * to read each file within the directory. */ public class ReadMultipleFilesFromADirectory { private static final String carriageReturn = "\n"; /** * * Note that this directory should be in the project/application * * root directory. * * * If you want to read all the files from a directory thats * * outside the root directory, use the absolute path i.e. * * c:/xyz/multipleFilesDirectory */ private static String multipleFilesDirectory = "multipleFilesDirectory"; public ReadMultipleFilesFromADirectory() { readMultipleFilesFromADirectory(); } private static void readMultipleFilesFromADirectory() { File directory = new File(multipleFilesDirectory); // just to double check that this is a directory if (directory.isDirectory()) { File[] allFilesWithinThisDirectory = directory.listFiles(); System.out.println("About to read " + allFilesWithinThisDirectory.length + " within the directory " + directory.getAbsolutePath()); for (File file : allFilesWithinThisDirectory) { System.out.println("\n** About to read a file " + file.getName() + " **"); String fileContents = readFile(file.getAbsolutePath()); System.out.println("The file contents are:"); System.out.println(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 static 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(); } /** * * @param args */ public static void main(String[] args) { new ReadMultipleFilesFromADirectory(); } }
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.
