Here you can find the source of readTextFile(File file)
Parameter | Description |
---|---|
file | The file. |
Parameter | Description |
---|---|
IOException | If the file could not be read. |
public static String readTextFile(File file) throws IOException
//package com.java2s; // Licensed under the Apache License, Version 2.0 (the "License"); import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class Main { /** Platform specific NEWLINE character. */ private static final String NEWLINE = System.getProperty("line.separator"); /**/*from w ww . j a v a2s . co m*/ * Reads the content of a text file. * * @param file * The file. * @return The content. * * @throws IOException * If the file could not be read. */ public static String readTextFile(File file) throws IOException { if (!file.isFile()) { throw new IllegalArgumentException("File not found: " + file.getAbsolutePath()); } if (!file.canRead()) { throw new IllegalArgumentException("File not readable: " + file.getAbsolutePath()); } String content = null; BufferedReader br = null; try { br = new BufferedReader(new FileReader(file)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { sb.append(line).append(NEWLINE); } content = sb.toString(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { // Best effort; ignore. } } } return content; } }