One of the simplest ways to read in a text file in Java is to use the readLine() method to read one line at a time. In this example the file is opened with a FileReader, buffered with a BufferedReader, and then read in using the readLine() method.
import java.io.*; public class ReadTextFile { public static void main(String[] args) { StringBuilder contents = new StringBuilder(); try { BufferedReader input = new BufferedReader(new FileReader("C:\\Temp\\myFile.txt")); try { String line = null; while (( line = input.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } System.out.println(contents.toString()); } }
This same functionality can be put into a static method and then used throughout a program.
import java.io.*; public class ReadTextFile { public static void main(String[] args) throws FileNotFoundException { File testFile = new File("C:\\Temp\\myFile.txt"); System.out.println("Contents of File:n" + fileToString(testFile)); } static public String fileToString(File textFile) throws FileNotFoundException { // Checks if file exists if (!textFile.exists()) { throw new FileNotFoundException ("File does not exist: " + textFile); } StringBuilder contents = new StringBuilder(); try { BufferedReader input = new BufferedReader(new FileReader(textFile)); try { String line = null; while (( line = input.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents.toString(); } }
