Here you can find the source of readTextFile(File f, int maxNumLines)
Parameter | Description |
---|---|
maxNumLines | max number of lines (greater than zero) |
private static String readTextFile(File f, int maxNumLines)
//package com.java2s; //License from project: Open Source License import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Main { /**// w w w . j av a 2s .co m * Read in the last few lines of a (newline delimited) textfile, or null if * the file doesn't exist. * * Same as FileUtil.readTextFile but uses platform encoding, * not UTF-8, since the wrapper log cannot be configured: * http://stackoverflow.com/questions/14887690/how-do-i-get-the-tanuki-wrapper-log-files-to-be-utf-8-encoded * * Warning - this inefficiently allocates a StringBuilder of size maxNumLines*80, * so don't make it too big. * Warning - converts \r\n to \n * * @param maxNumLines max number of lines (greater than zero) * @return string or null; does not throw IOException. * @since 0.9.11 modded from FileUtil.readTextFile() */ private static String readTextFile(File f, int maxNumLines) { if (!f.exists()) return null; FileInputStream fis = null; BufferedReader in = null; try { fis = new FileInputStream(f); in = new BufferedReader(new InputStreamReader(fis)); List<String> lines = new ArrayList<String>(maxNumLines); String line = null; while ((line = in.readLine()) != null) { lines.add(line); if (lines.size() >= maxNumLines) lines.remove(0); } StringBuilder buf = new StringBuilder(lines.size() * 80); for (int i = 0; i < lines.size(); i++) { buf.append(lines.get(i)).append('\n'); } return buf.toString(); } catch (IOException ioe) { return null; } finally { if (in != null) try { in.close(); } catch (IOException ioe) { } } } }