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:com.jaspersoft.jasperserver.war.OlapGetChart.java

/**
 * Binary streams the specified file to the HTTP response in 1KB chunks
 *
 * @param file The file to be streamed.//w  w w .  j  av  a  2 s  .c om
 * @param response The HTTP response object.
 * @param mimeType The mime type of the file, null allowed.
 *
 * @throws IOException  if there is an I/O problem.
 * @throws FileNotFoundException  if the file is not found.
 */
public static void sendTempFile(File file, HttpServletResponse response, String mimeType)
        throws IOException, FileNotFoundException {

    if (file.exists()) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

        //  Set HTTP headers
        if (mimeType != null) {
            response.setHeader("Content-Type", mimeType);
        }
        response.setHeader("Content-Length", String.valueOf(file.length()));
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        response.setHeader("Last-Modified", sdf.format(new Date(file.lastModified())));

        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        byte[] input = new byte[1024];
        boolean eof = false;
        while (!eof) {
            int length = bis.read(input);
            if (length == -1) {
                eof = true;
            } else {
                bos.write(input, 0, length);
            }
        }
        bos.flush();
        bis.close();
        bos.close();
    } else {
        throw new FileNotFoundException(file.getAbsolutePath());
    }
    return;
}

From source file:ispyb.client.common.util.FileUtil.java

/**
 * Gunzip a local file//from www.  j  av  a2 s.c  om
 * 
 * @param sourceFileName
 * @return
 */

public static byte[] readBytes(String sourceFileName) {

    ByteArrayOutputStream outBuffer = null;
    FileInputStream inFile = null;
    BufferedInputStream bufInputStream = null;

    try {
        outBuffer = new ByteArrayOutputStream();
        inFile = new FileInputStream(sourceFileName);
        bufInputStream = new BufferedInputStream(inFile);

        byte[] tmpBuffer = new byte[8 * 1024];
        int n = 0;
        while ((n = bufInputStream.read(tmpBuffer)) >= 0)
            outBuffer.write(tmpBuffer, 0, n);
    } catch (FileNotFoundException fnf) {
        LOG.error("[readBytes] File not found :" + fnf.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (inFile != null) {
            try {
                inFile.close();
            } catch (IOException ioex) {
                // ignore
            }
        }
        if (outBuffer != null) {
            try {
                outBuffer.close();
            } catch (IOException ioex) {
                // ignore
            }
        }
        if (bufInputStream != null) {
            try {
                bufInputStream.close();
            } catch (IOException ioex) {
                // ignore
            }
        }
    }
    return outBuffer.toByteArray();
}

From source file:Files.java

/**
 * Copy a file./* w  w  w . j  a v a  2  s.  com*/
 *
 * @param source  Source file to copy.
 * @param target  Destination target file.
 * @param buff    The copy buffer.
 *
 * @throws IOException  Failed to copy file.
 */
public static void copy(final File source, final File target, final byte buff[]) throws IOException {
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target));

    int read;

    try {
        while ((read = in.read(buff)) != -1) {
            out.write(buff, 0, read);
        }
    } finally {
        Streams.flush(out);
        Streams.close(in);
        Streams.close(out);
    }
}

From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

public static void addFolderToZip(File folder, String parentFolder, ZipOutputStream zos) throws Exception {

    for (File file : folder.listFiles()) {

        if (file.isDirectory()) {
            zos.putNextEntry(new ZipEntry(parentFolder + file.getName() + "/"));
            zos.closeEntry();/*from   w w w . j  a  v a 2  s.c o  m*/
            addFolderToZip(file, parentFolder + file.getName() + "/", zos);
            continue;
        } else {
            zos.putNextEntry(new ZipEntry(parentFolder + file.getName()));
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

            long bytesRead = 0;
            byte[] bytesIn = new byte[1024];
            int read = 0;

            while ((read = bis.read(bytesIn)) != -1) {
                zos.write(bytesIn, 0, read);
                bytesRead += read;
            }

            zos.closeEntry();
            bis.close();
        }
    }
}

From source file:net.librec.util.FileUtil.java

/**
 * Zip a given folder//from w ww  .  java2s . co  m
 *
 * @param dirPath    a given folder: must be all files (not sub-folders)
 * @param filePath   zipped file
 * @throws Exception if error occurs
 */
public static void zipFolder(String dirPath, String filePath) throws Exception {
    File outFile = new File(filePath);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outFile));
    int bytesRead;
    byte[] buffer = new byte[1024];
    CRC32 crc = new CRC32();
    for (File file : listFiles(dirPath)) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        crc.reset();
        while ((bytesRead = bis.read(buffer)) != -1) {
            crc.update(buffer, 0, bytesRead);
        }
        bis.close();

        // Reset to beginning of input stream
        bis = new BufferedInputStream(new FileInputStream(file));
        ZipEntry entry = new ZipEntry(file.getName());
        entry.setMethod(ZipEntry.STORED);
        entry.setCompressedSize(file.length());
        entry.setSize(file.length());
        entry.setCrc(crc.getValue());
        zos.putNextEntry(entry);
        while ((bytesRead = bis.read(buffer)) != -1) {
            zos.write(buffer, 0, bytesRead);
        }
        bis.close();
    }
    zos.close();

    LOG.debug("A zip-file is created to: " + outFile.getPath());
}

From source file:adams.core.io.Bzip2Utils.java

/**
 * Compresses the specified file./*from  ww w  .  j a  v a 2s.  c o  m*/
 * <br><br>
 * See <a href="https://commons.apache.org/compress/examples.html" target="_blank">Apache commons/compress</a>.
 *
 * @param inputFile   the file to compress
 * @param buffer   the buffer size to use
 * @param outputFile   the destination file (the archive)
 * @param removeInput   whether to remove the input file
 * @return      the error message, null if everything OK
 */
public static String compress(File inputFile, int buffer, File outputFile, boolean removeInput) {
    String result;
    byte[] buf;
    int len;
    BZip2CompressorOutputStream out;
    BufferedInputStream in;
    String msg;
    FileInputStream fis;
    FileOutputStream fos;

    in = null;
    fis = null;
    out = null;
    fos = null;
    result = null;
    try {
        // does file already exist?
        if (outputFile.exists())
            System.err.println("WARNING: overwriting '" + outputFile + "'!");

        // create GZIP file
        buf = new byte[buffer];
        fos = new FileOutputStream(outputFile);
        out = new BZip2CompressorOutputStream(fos);
        fis = new FileInputStream(inputFile.getAbsolutePath());
        in = new BufferedInputStream(fis);

        // Transfer bytes from the file to the GZIP file
        while ((len = in.read(buf)) > 0)
            out.write(buf, 0, len);

        FileUtils.closeQuietly(in);
        FileUtils.closeQuietly(fis);
        FileUtils.closeQuietly(out);
        FileUtils.closeQuietly(fos);
        in = null;
        fis = null;
        out = null;
        fos = null;

        // remove input file?
        if (removeInput) {
            if (!inputFile.delete())
                result = "Failed to delete input file '" + inputFile + "' after successful compression!";
        }
    } catch (Exception e) {
        msg = "Failed to compress '" + inputFile + "': ";
        System.err.println(msg);
        e.printStackTrace();
        result = msg + e;
    } finally {
        FileUtils.closeQuietly(in);
        FileUtils.closeQuietly(fis);
        FileUtils.closeQuietly(out);
        FileUtils.closeQuietly(fos);
    }

    return result;
}

From source file:com.piaoyou.util.FileUtil.java

/**
 * This method write srcFile to the output, and does not close the output
 * @param srcFile File the source (input) file
 * @param output OutputStream the stream to write to, this method will not buffered the output
 * @throws IOException//from  ww w.  j  a  v a2  s.c  o m
 */
public static void popFile(File srcFile, OutputStream output) throws IOException {

    BufferedInputStream input = null;
    byte[] block = new byte[4096];
    try {
        input = new BufferedInputStream(new FileInputStream(srcFile), 4096);
        while (true) {
            int length = input.read(block);
            if (length == -1)
                break;// end of file
            output.write(block, 0, length);
        }
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException ex) {
                log.error("Cannot close stream", ex);
            }
        }
    }
}

From source file:hd3gtv.mydmam.metadata.RenderedFile.java

/**
 * Test presence and validity for file.//www  .  jav  a 2s  .c o  m
 */
public static RenderedFile import_from_entry(RenderedContent content, String metadata_reference_id,
        boolean check_hash) throws IOException {
    if (content == null) {
        throw new NullPointerException("\"content\" can't to be null");
    }

    if (metadata_reference_id == null) {
        throw new NullPointerException("\"metadata_reference_id\" can't to be null");
    }

    if (local_directory == null) {
        throw new IOException("No configuration is set !");
    }
    if (local_directory.exists() == false) {
        throw new IOException("Invalid configuration is set !");
    }

    RenderedFile result = new RenderedFile();

    StringBuffer sb_rendered_file = new StringBuffer();
    sb_rendered_file.append(local_directory.getCanonicalPath());
    sb_rendered_file.append(File.separator);
    sb_rendered_file.append(metadata_reference_id.substring(0, 6));
    sb_rendered_file.append(File.separator);
    sb_rendered_file.append(metadata_reference_id.substring(6));
    sb_rendered_file.append(File.separator);
    sb_rendered_file.append(content.name);
    result.rendered_file = new File(sb_rendered_file.toString());

    if (result.rendered_file.exists() == false) {
        throw new FileNotFoundException("Can't found rendered file " + sb_rendered_file.toString());
    }

    if (result.rendered_file.length() != content.size) {
        throw new FileNotFoundException(
                "Rendered file has not the expected size " + sb_rendered_file.toString());
    }

    if (check_hash) {
        result.rendered_digest = (String) content.hash;

        MessageDigest mdigest = null;
        try {
            mdigest = MessageDigest.getInstance(digest_algorithm);
        } catch (NoSuchAlgorithmException e) {
        }
        BufferedInputStream source_stream = new BufferedInputStream(new FileInputStream(result.rendered_file),
                0xFFF);
        int len;
        byte[] buffer = new byte[0xFFF];
        while ((len = source_stream.read(buffer)) > 0) {
            mdigest.update(buffer, 0, len);
        }
        source_stream.close();
        String file_digest = MyDMAM.byteToString(mdigest.digest());

        if (file_digest.equalsIgnoreCase(result.rendered_digest) == false) {
            Log2Dump dump = new Log2Dump();
            dump.add("source", sb_rendered_file);
            dump.add("source", file_digest);
            dump.add("expected", content);
            dump.add("expected", result.rendered_digest);
            Log2.log.error("Invalid " + digest_algorithm + " check", null, dump);
            throw new FileNotFoundException(
                    "Rendered file has not the expected content " + sb_rendered_file.toString());
        }
    }
    result.rendered_mime = content.mime;
    result.consolidated = true;
    return result;
}

From source file:edu.ucsb.eucalyptus.admin.server.EucalyptusWebBackendImpl.java

private static String readFileAsString(String filePath) throws java.io.IOException {
    byte[] buffer = new byte[(int) new File(filePath).length()];
    BufferedInputStream f = null;
    try {//from w  ww. j a v a 2s .c o  m
        f = new BufferedInputStream(new FileInputStream(filePath));
        f.read(buffer);
    } finally {
        if (f != null)
            try {
                f.close();
            } catch (IOException ignored) {
            }
    }
    return new String(buffer);
}

From source file:com.piaoyou.util.FileUtil.java

public static byte[] getBytes(InputStream inputStream) throws IOException {
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
    byte[] block = new byte[4096];
    while (true) {
        int readLength = bufferedInputStream.read(block);
        if (readLength == -1)
            break;// end of file
        byteArrayOutputStream.write(block, 0, readLength);
    }//from   ww  w  .  ja  va2  s  .  co m
    byte[] retValue = byteArrayOutputStream.toByteArray();
    byteArrayOutputStream.close();
    return retValue;
}