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) 

Method Source Code

//package com.java2s;
/*//from w w w .j  a v  a 2 s . co m
 * Copyright (c) 2004-2012 The YAWL Foundation. All rights reserved.
 * The YAWL Foundation is a collaboration of individuals and
 * organisations who are committed to improving workflow technology.
 *
 * This file is part of YAWL. YAWL 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.
 *
 * YAWL 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 YAWL. If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.*;

public class Main {
    public static String fileToString(File f) {
        if (f.exists()) {
            try {
                int bufsize = (int) f.length();
                InputStream fis = new FileInputStream(f);
                return streamToString(fis, bufsize);
            } catch (Exception e) {
                return null;
            }
        } else
            return null;
    }

    public static String fileToString(String filename) {
        return fileToString(new File(filename));
    }

    public static String streamToString(InputStream is) {
        return streamToString(is, 32768); // default bufsize
    }

    public static String streamToString(InputStream is, int bufSize) {
        try {

            // read reply into a buffered byte stream - to preserve UTF-8
            BufferedInputStream inStream = new BufferedInputStream(is);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream(bufSize);
            byte[] buffer = new byte[bufSize];
            int bytesRead;

            while ((bytesRead = inStream.read(buffer, 0, bufSize)) > 0) {
                outStream.write(buffer, 0, bytesRead);
            }

            outStream.close();
            inStream.close();

            // convert the bytes to a UTF-8 string
            return outStream.toString("UTF-8");

        } catch (IOException ioe) {
            return null;
        }
    }
}

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)
  9. fileToString(File f)