Here you can find the source of readTextFile(String filename, int maxNumLines, boolean startAtBeginning)
Parameter | Description |
---|---|
startAtBeginning | if true, read the first maxNumLines, otherwise read the last maxNumLines |
maxNumLines | max number of lines (or -1 for unlimited) |
public static String readTextFile(String filename, int maxNumLines, boolean startAtBeginning)
//package com.java2s; //License from project: Open Source License import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Main { /**/*from w w w.j ava 2 s .c o m*/ * Read in the last few lines of a (newline delimited) textfile, or null if * the file doesn't exist. * * Warning - this inefficiently allocates a StringBuilder of size maxNumLines*80, * so don't make it too big. * Warning - converts \r\n to \n * * @param startAtBeginning if true, read the first maxNumLines, otherwise read * the last maxNumLines * @param maxNumLines max number of lines (or -1 for unlimited) * @return string or null; does not throw IOException. * */ public static String readTextFile(String filename, int maxNumLines, boolean startAtBeginning) { File f = new File(filename); if (!f.exists()) return null; FileInputStream fis = null; BufferedReader in = null; try { fis = new FileInputStream(f); in = new BufferedReader(new InputStreamReader(fis, "UTF-8")); List<String> lines = new ArrayList<String>(maxNumLines > 0 ? maxNumLines : 64); String line = null; while ((line = in.readLine()) != null) { lines.add(line); if ((maxNumLines > 0) && (lines.size() >= maxNumLines)) { if (startAtBeginning) break; else 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) { } } } }