Java File to String fileToString(File f)

Here you can find the source of fileToString(File f)

Description

file To String

License

Open Source License

Declaration

public static String fileToString(File f) throws IOException 

Method Source Code


//package com.java2s;
/*//from   w  ww  .  j a  va  2  s . c  o m
 * Spirit, a study/biosample management tool for research.
 * Copyright (C) 2018 Idorsia Pharmaceuticals Ltd., Hegenheimermattweg 91,
 * CH-4123 Allschwil, Switzerland.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 * @author Joel Freyss
 */

import java.io.BufferedReader;

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.Reader;

public class Main {
    public static String fileToString(File f) throws IOException {
        return fileToString(f, Integer.MAX_VALUE);
    }

    public static String fileToString(File f, int maxSize) throws IOException {
        try (Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"))) {
            return readerToString(reader, maxSize);
        }
    }

    public static String readerToString(Reader reader) throws IOException {
        return readerToString(reader, Integer.MAX_VALUE);
    }

    public static String readerToString(Reader reader, int maxSize) throws IOException {
        char[] buf = new char[512];
        int c;
        StringBuilder sb = new StringBuilder();
        while (sb.length() < maxSize
                && (c = reader.read(buf, 0, Math.min(buf.length, maxSize - sb.length()))) > 0) {
            sb.append(buf, 0, c);
        }
        String s = sb.toString();

        //Remove BOM
        if (s.startsWith("\uFEFF"))
            s = s.substring(1);
        return s;
    }
}

Related

  1. fileToStr(String strInput)
  2. fileToStream(File source, OutputStream target)
  3. fileToStream(final File file)
  4. fileToStream(String filename)
  5. fileToString(File f)
  6. fileToString(File f)
  7. fileToString(File f)
  8. fileToString(File f)