Java ByteArrayOutputStream Write loadAFileToString(File f)

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

Description

load A File To String

License

Apache License

Declaration

public static String loadAFileToString(File f) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    public static String loadAFileToString(File f) {
        InputStream is = null;//from w  w  w. j  av a2  s .  c  o  m
        String ret = null;
        try {
            is = new BufferedInputStream(new FileInputStream(f));
            long contentLength = f.length();
            ByteArrayOutputStream outstream = new ByteArrayOutputStream(
                    contentLength > 0 ? (int) contentLength : 1024);
            byte[] buffer = new byte[4096];
            int len;
            while ((len = is.read(buffer)) > 0) {
                outstream.write(buffer, 0, len);
            }
            outstream.close();
            ret = new String(outstream.toByteArray(), "utf-8");
        } catch (IOException e) {
            ret = "";
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
        }
        return ret;
    }
}

Related

  1. load(InputStream in, byte[] buffer, int offset, int initialBufferSize)
  2. load(InputStream inputStream, Class type)
  3. load(InputStream is)
  4. load(InputStream is, boolean close)
  5. load(String fileName)
  6. loadAsciiTxt()
  7. loadAsText(Class cls, String name)
  8. loadBinFile(java.io.File f)
  9. loadFully(final InputStream aStream)