Java File to String fileToString(final File file)

Here you can find the source of fileToString(final File file)

Description

file To String

License

Open Source License

Declaration

@SuppressWarnings({ "IOResourceOpenedButNotSafelyClosed", "HardCodedStringLiteral" })
    public static String fileToString(final File file) throws IOException 

Method Source Code


//package com.java2s;
/*// w w w .ja  v a 2 s .com
 * Copyright 2008-2013 Andre Pfeiler
 *
 * This file is part of FindBugs-IDEA.
 *
 * FindBugs-IDEA 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.
 *
 * FindBugs-IDEA 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 FindBugs-IDEA.  If not, see <http://www.gnu.org/licenses/>.
 */

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

public class Main {
    @SuppressWarnings({ "IOResourceOpenedButNotSafelyClosed", "HardCodedStringLiteral" })
    public static String fileToString(final File file) throws IOException {
        FileInputStream in = null;
        int size = 0;
        if (file.exists()) {
            in = new FileInputStream(file);
            size = (int) file.length();
        }

        try {
            int fRead = 0;
            final byte[] fBuffer = new byte[size];
            while (fRead < size) {
                if (in != null) {
                    fRead += in.read(fBuffer, fRead, size - fRead);
                }
            }
            if (in != null) {
                in.close();
            }
            return new String(fBuffer, "UTF-8");
        } catch (final IOException ex) {
            throw new IOException("could not read configuration file '" + file.getPath() + "': " + ex.getMessage());
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

Related

  1. fileToString(File file)
  2. fileToString(File file, int max)
  3. fileToString(File file, String charsetName)
  4. fileToString(File file, String charsetName)
  5. fileToString(File files[])
  6. fileToString(final File file, final String charsetName)
  7. fileToString(final String filePath)
  8. fileToString(InputStream file)
  9. fileToString(InputStream inputStream)