Java BufferedReader Read readFile(File f, boolean preserveLineBreaks)

Here you can find the source of readFile(File f, boolean preserveLineBreaks)

Description

read File

License

Open Source License

Parameter

Parameter Description
f - file name

Return

File contents as string

Declaration

private static String readFile(File f, boolean preserveLineBreaks) 

Method Source Code


//package com.java2s;
/*// w w  w .j  av a  2s .c o m
 * Copyright (c) 2013. Chandra Tungaturthi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.*;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {
    public final static String WORD_BREAK = " ";
    public final static String LINE_BREAK = System.getProperty("line.separator");
    private static final Logger mylogger = Logger.getLogger("com.lia.core");

    /**
     *
     * @param f - file name
     * @return File contents as string
     */
    private static String readFile(File f, boolean preserveLineBreaks) {

        StringBuilder content = new StringBuilder();
        String line = null;
        BufferedReader br = null;
        try {

            mylogger.log(Level.INFO, "Reading: [{0}] File: [{1}]",
                    new Object[] { f.getName(), f.getAbsolutePath() });
            br = new BufferedReader(new FileReader(f));
            while ((line = br.readLine()) != null) {
                if (preserveLineBreaks) {
                    content.append(line).append(LINE_BREAK);

                } else {
                    content.append(line).append(WORD_BREAK);
                }
            }

        } catch (FileNotFoundException ex) {
            mylogger.log(Level.SEVERE, "Error:", ex);
        } finally {

            try {

                br.close();
            } catch (IOException ex) {
                mylogger.log(Level.SEVERE, "Error:", ex);
            }
            return content.toString();
        }
    }
}

Related

  1. readFile(File f)
  2. readFile(File f)
  3. readFile(File f)
  4. readFile(File f)
  5. ReadFile(File f, boolean keep_newline)
  6. readFile(File f, String newLineChar)
  7. readFile(File file)
  8. readFile(File file)
  9. readFile(File file)