Example usage for java.io BufferedInputStream read

List of usage examples for java.io BufferedInputStream read

Introduction

In this page you can find the example usage for java.io BufferedInputStream read.

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:Main.java

/**
 * Utility method that creates a <code>UIDefaults.LazyValue</code> that
 * creates an <code>ImageIcon</code> <code>UIResource</code> for the
 * specified image file name. The image is loaded using
 * <code>getResourceAsStream</code>, starting with a call to that method
 * on the base class parameter. If it cannot be found, searching will
 * continue through the base class' inheritance hierarchy, up to and
 * including <code>rootClass</code>.
 *
 * @param baseClass the first class to use in searching for the resource
 * @param rootClass an ancestor of <code>baseClass</code> to finish the
 *                  search at/*from  w  w  w. j  a  v a2  s.  c o  m*/
 * @param imageFile the name of the file to be found
 * @return a lazy value that creates the <code>ImageIcon</code>
 *         <code>UIResource</code> for the image,
 *         or null if it cannot be found
 */
public static Object makeIcon(final Class<?> baseClass, final Class<?> rootClass, final String imageFile) {

    return new UIDefaults.LazyValue() {
        public Object createValue(UIDefaults table) {
            /* Copy resource into a byte array.  This is
             * necessary because several browsers consider
             * Class.getResource a security risk because it
             * can be used to load additional classes.
             * Class.getResourceAsStream just returns raw
             * bytes, which we can convert to an image.
             */
            byte[] buffer = java.security.AccessController
                    .doPrivileged(new java.security.PrivilegedAction<byte[]>() {
                        public byte[] run() {
                            try {
                                InputStream resource = null;
                                Class<?> srchClass = baseClass;

                                while (srchClass != null) {
                                    resource = srchClass.getResourceAsStream(imageFile);

                                    if (resource != null || srchClass == rootClass) {
                                        break;
                                    }

                                    srchClass = srchClass.getSuperclass();
                                }

                                if (resource == null) {
                                    return null;
                                }

                                BufferedInputStream in = new BufferedInputStream(resource);
                                ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
                                byte[] buffer = new byte[1024];
                                int n;
                                while ((n = in.read(buffer)) > 0) {
                                    out.write(buffer, 0, n);
                                }
                                in.close();
                                out.flush();
                                return out.toByteArray();
                            } catch (IOException ioe) {
                                System.err.println(ioe.toString());
                            }
                            return null;
                        }
                    });

            if (buffer == null) {
                return null;
            }
            if (buffer.length == 0) {
                System.err.println("warning: " + imageFile + " is zero-length");
                return null;
            }

            return new ImageIconUIResource(buffer);
        }
    };
}

From source file:com.pactera.edg.am.metamanager.extractor.util.AntZip.java

/**
 * ?zip/*from w w w  .  ja va 2  s .c  o m*/
 * 
 * @param source
 * @param basePath
 *            
 * @param zos
 */

private static void zipFile(File source, String basePath,

        ZipOutputStream zos) {

    File[] files = new File[0];

    if (source.isDirectory()) {

        files = source.listFiles();

    } else {

        files = new File[1];

        files[0] = source;

    }

    String pathName;// ()

    byte[] buf = new byte[1024];

    int length = 0;

    try {

        for (File file : files) {

            if (file.isDirectory()) {

                pathName = file.getPath().substring(basePath.length() + 1)

                        + "/";

                zos.putNextEntry(new ZipEntry(pathName));

                zipFile(file, basePath, zos);

            } else {

                pathName = file.getPath().substring(basePath.length() + 1);

                InputStream is = new FileInputStream(file);

                BufferedInputStream bis = new BufferedInputStream(is);

                zos.putNextEntry(new ZipEntry(pathName));

                while ((length = bis.read(buf)) > 0) {

                    zos.write(buf, 0, length);

                }

                is.close();

            }

        }

    } catch (Exception e) {

        e.printStackTrace();

    }

}

From source file:edu.isi.wings.portal.classes.StorageHandler.java

private static void zipAndStream(File dir, ZipOutputStream zos, String prefix) throws Exception {
    byte bytes[] = new byte[2048];
    for (File file : dir.listFiles()) {
        if (file.isDirectory())
            StorageHandler.zipAndStream(file, zos, prefix + file.getName() + "/");
        else {/*from   ww w . j a  v  a 2s.  c om*/
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            BufferedInputStream bis = new BufferedInputStream(fis);
            zos.putNextEntry(new ZipEntry(prefix + file.getName()));
            int bytesRead;
            while ((bytesRead = bis.read(bytes)) != -1) {
                zos.write(bytes, 0, bytesRead);
            }
            zos.closeEntry();
            bis.close();
            fis.close();
        }
    }
}

From source file:eu.scape_project.spacip.ContainerProcessing.java

/**
 * Write ARC record content to output stream
 *
 * @param nativeArchiveRecord//from   ww  w .java2  s .co  m
 * @param outputStream Output stream
 * @throws IOException
 */
public static void recordToOutputStream(ArchiveRecord nativeArchiveRecord, OutputStream outputStream)
        throws IOException {
    ARCRecord arcRecord = (ARCRecord) nativeArchiveRecord;
    ARCRecordMetaData metaData = arcRecord.getMetaData();
    long contentBegin = metaData.getContentBegin();
    BufferedInputStream bis = new BufferedInputStream(arcRecord);
    BufferedOutputStream bos = new BufferedOutputStream(outputStream);
    byte[] tempBuffer = new byte[BUFFER_SIZE];
    int bytesRead;
    // skip record header
    bis.skip(contentBegin);
    while ((bytesRead = bis.read(tempBuffer)) != -1) {
        bos.write(tempBuffer, 0, bytesRead);
    }
    bos.flush();
    bis.close();
    bos.close();
}

From source file:com.wareninja.opensource.gravatar4android.common.Utils.java

public static byte[] downloadImage_alternative2(String url) throws GenericException {

    byte[] imageData = null;
    try {/*from   w  ww . j a  va 2 s.  co m*/

        URLConnection connection = new URL(url).openConnection();

        InputStream stream = connection.getInputStream();

        //BufferedInputStream in=new BufferedInputStream(stream);//default 8k buffer
        BufferedInputStream in = new BufferedInputStream(stream, 10240);// 10k=10240, 2x8k=16384
        ByteArrayOutputStream out = new ByteArrayOutputStream(10240);
        int read;
        byte[] b = new byte[4096];

        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }

        out.flush();
        out.close();

        imageData = out.toByteArray();
    } catch (FileNotFoundException e) {
        return null;
    } catch (Exception e) {

        Log.w(TAG, "Exc=" + e);
        throw new GenericException(e);
    }

    return imageData;
}

From source file:net.vexelon.myglob.utils.Utils.java

/**
 * Write input stream data to PRIVATE internal storage file.
 * @param context//from  w  w w .j  a va 2s  .  com
 * @param source
 * @param internalStorageName
 * @throws IOException
 */
public static void writeToInternalStorage(Context context, InputStream source, String internalStorageName)
        throws IOException {

    FileOutputStream fos = null;
    try {
        fos = context.openFileOutput(internalStorageName, Context.MODE_PRIVATE);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        BufferedInputStream bis = new BufferedInputStream(source);
        byte[] buffer = new byte[4096];
        int read = -1;
        while ((read = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, read);
        }
        bos.flush();
        bos.close();
    } catch (FileNotFoundException e) {
        throw new IOException(e.getMessage());
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
        try {
            if (source != null)
                source.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.antelink.sourcesquare.client.scan.FileAnalyzer.java

/**
 * Computes the hash of a given file./*from  ww  w  .jav a  2 s .co  m*/
 * 
 * @param hashType
 *            Hash that you want to compute. Usually SHA-1 or MD5 (or any
 *            other kind supported by java.security.MessageDigest).
 * @param fileToAnalyze
 *            Descriptor of the file to analyze. Must be a file otherwise
 *            you will get an exception.
 * @return the String hexadecimal representation of the file hash.
 * @throws NoSuchAlgorithmException
 *             if hashType is not a supported hash algorithm
 * @throws IOException
 *             in case of an I/O error while reading file
 */
public static String calculateHash(String hashType, File fileToAnalyze)
        throws NoSuchAlgorithmException, IOException {
    FileInputStream fis = null;
    BufferedInputStream inputStream = null;
    try {
        logger.debug("Calculating sha1 for file " + fileToAnalyze.getName());
        fis = new FileInputStream(fileToAnalyze);
        inputStream = new BufferedInputStream(fis);
        MessageDigest digest = MessageDigest.getInstance(hashType);
        byte[] buffer = new byte[1024 * 1024];
        int length = -1;
        while ((length = inputStream.read(buffer)) != -1) {
            digest.update(buffer, 0, length);
        }

        String hash = new String(Hex.encodeHex(digest.digest()));
        logger.debug("Sha1 calculated for file " + fileToAnalyze.getName());
        return hash;
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(fis);
    }
}

From source file:com.DPFaragir.DPFUtils.java

public static String loadFileAsString(String filename) throws java.io.IOException {
    final int BUFLEN = 1024;
    BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
    try {//from   w  w w  . j ava 2 s. c  om
        ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
        byte[] bytes = new byte[BUFLEN];
        boolean isUTF8 = false;
        int read, count = 0;
        while ((read = is.read(bytes)) != -1) {
            if (count == 0 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
                isUTF8 = true;
                baos.write(bytes, 3, read - 3); // drop UTF8 bom marker
            } else {
                baos.write(bytes, 0, read);
            }
            count += read;
        }
        return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
    } finally {
        try {
            is.close();
        } catch (Exception ex) {
        }
    }
}

From source file:edu.du.penrose.systems.fedoraProxy.web.bus.ProxyController.java

/**
 * Call the HttpMethod and write all results and status to the HTTP response
 * object.//ww  w. j ava  2 s  . co  m
 * 
 * THIS IS THE REQUEST WE NEED TO DUPLICATE GET
 * /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1 Host: localhost:8080
 * Connection: keep-alive Accept:
 * application/xml,application/xhtml+xml,text/
 * html;q=0.9,text/plain;q=0.8,image/png,*;q=0.5 User-Agent: Mozilla/5.0
 * (X11; U; Linux x86_64; en-US) AppleWebKit/534.10 (KHTML, like Gecko)
 * Chrome/8.0.552.215 Safari/534.10 Accept-Encoding: gzip,deflate,sdch
 * Accept-Language: en-US,en;q=0.8 Accept-Charset:
 * ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: fez_list=YjowOw%3D%3D
 * 
 * ACTUAL SENT GET /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1
 * Accept:
 * application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q
 * =0.8,image/png,*;q=0.5 Connection: keep-alive Accept-Encoding:
 * gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset:
 * ISO-8859-1,utf-8;q=0.7,*;q=0.3 : User-Agent: Jakarta
 * Commons-HttpClient/3.1 Host: localhost:8080
 * 
 * @param proxyCommand
 * @param response
 * @param authenicate true to set Preemptive authentication
 */
public static void executeMethod(String proxyCommand, HttpServletResponse response, boolean authenicate) {
    HttpClient theClient = new HttpClient();

    HttpMethod method = new GetMethod(proxyCommand);

    setDefaultHeaders(method);

    setAdrCredentials(theClient, authenicate);

    try {
        theClient.executeMethod(method);
        response.setStatus(method.getStatusCode());

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {

            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }

            /**
             * Copy all headers, except Transfer-Encoding which is getting set
             * set elsewhere. At this point response.containsHeader(
             * "Transfer-Encoding" ) is false, however it is getting set twice
             * according to wireshark, therefore we do not set it here.
             */
            if (!header.getName().equalsIgnoreCase("Transfer-Encoding")) {
                response.setHeader(header.getName(), header.getValue());
            }
        }

        // Write the body, flush and close

        InputStream is = method.getResponseBodyAsStream();

        BufferedInputStream bis = new BufferedInputStream(is);

        StringBuffer sb = new StringBuffer();
        byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
        int count = bis.read(bytes);
        while (count != -1 && count <= 8192) {
            response.getOutputStream().write(bytes, 0, count);
            count = bis.read(bytes);
        }

        bis.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {
        method.releaseConnection();
    }
}

From source file:com.github.pitzcarraldo.openjpeg.OpenJPEGLoader.java

private static void copyStreamToFile(InputStream pInputStream, File pFile) throws IOException {
    BufferedInputStream bis = new BufferedInputStream(pInputStream);
    FileOutputStream fos = new FileOutputStream(pFile.getAbsolutePath());
    byte[] buffer = new byte[32768];
    int bytesRead = 0;
    while (bis.available() > 0) {
        bytesRead = bis.read(buffer);
        fos.write(buffer, 0, bytesRead);
    }/* w w w  .j a  v a2s  .  c  o  m*/
    bis.close();
    fos.close();
    pFile.deleteOnExit();
}