Java InputStreamReader Create readTextFile(File f, int maxNumLines)

Here you can find the source of readTextFile(File f, int maxNumLines)

Description

Read in the last few lines of a (newline delimited) textfile, or null if the file doesn't exist.

License

Open Source License

Parameter

Parameter Description
maxNumLines max number of lines (greater than zero)

Return

string or null; does not throw IOException.

Declaration

private static String readTextFile(File f, int maxNumLines) 

Method Source Code


//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) {
                }
        }
    }
}

Related

  1. readTextFile(File f)
  2. readTextFile(File f)
  3. readTextFile(File f)
  4. readTextFile(File f)
  5. readTextFile(File f)
  6. readTextFile(File file)
  7. readTextFile(File file)
  8. readTextFile(File file, String charsetName)
  9. readTextFile(File fromFile)