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.feilong.commons.core.io.FileUtil.java

/**
 * ?ByteArray.//  w  w  w  .  j  a va  2  s. co  m
 *
 * @param file
 *            file
 * @return byteArrayOutputStream.toByteArray();
 * @throws UncheckedIOException
 *             the unchecked io exception
 */
public static final byte[] convertFileToByteArray(File file) throws UncheckedIOException {
    InputStream inputStream = FileUtil.getFileInputStream(file);

    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    byte[] bytes = new byte[IOConstants.DEFAULT_BUFFER_LENGTH];
    int j;

    try {
        while ((j = bufferedInputStream.read(bytes)) != -1) {
            byteArrayOutputStream.write(bytes, 0, j);
        }
        byteArrayOutputStream.flush();

        return byteArrayOutputStream.toByteArray();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        try {
            // ???StreamClose.??Close
            // finally Block??close()
            byteArrayOutputStream.close();
            bufferedInputStream.close();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

From source file:edu.stanford.epad.plugins.qifpwrapper.QIFPHandler.java

public static File generateZipFile(List<File> files, String dirPath) {

    File dir_file = new File(dirPath);
    File zip_file = new File(dirPath + "/temp_" + (fileNum++) + ".zip");
    int dir_l = dir_file.getAbsolutePath().length();

    FileOutputStream fos = null;// w ww.j av  a 2 s  . c  o  m
    try {
        fos = new FileOutputStream(zip_file);
    } catch (FileNotFoundException e1) {
        log.warning("File not found", e1);
        return null;
    }

    ZipOutputStream zipout = new ZipOutputStream(fos);
    zipout.setLevel(1);
    for (int i = 0; i < files.size(); i++) {
        File f = (File) files.get(i);
        if (f.canRead()) {
            log.info("Adding file: " + f.getAbsolutePath());
            try {
                zipout.putNextEntry(new ZipEntry(f.getAbsolutePath().substring(dir_l + 1)));
            } catch (Exception e) {
                log.warning("Error adding to zip file", e);
                return null;
            }
            BufferedInputStream fr;
            try {
                fr = new BufferedInputStream(new FileInputStream(f));

                byte buffer[] = new byte[0xffff];
                int b;
                while ((b = fr.read(buffer)) != -1)
                    zipout.write(buffer, 0, b);

                fr.close();
                zipout.closeEntry();

            } catch (Exception e) {
                log.warning("Error closing zip file", e);
                return null;
            }
        }
    }

    try {
        zipout.finish();
        fos.flush();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    log.info("file zipped and returning as " + zip_file.getAbsolutePath());
    return zip_file;

}

From source file:Thumbnail.java

public void doWork(String[] args) {
    try {/*from w ww . j  ava 2 s . c om*/
        byte[] bytes = new byte[50000];

        FileInputStream fs = new FileInputStream(args[2]);
        BufferedInputStream bis = new BufferedInputStream(fs);
        bis.read(bytes);

        ID id = new ID();
        id.nail_id = Integer.parseInt(args[0]);
        id.acc_id = Integer.parseInt(args[1]);

        statement = connection.prepareStatement("INSERT INTO thumbnail VALUES(?,?,?,?, 0, now())");

        statement.setInt(1, id.nail_id);
        statement.setInt(2, id.acc_id);
        statement.setBytes(3, bytes);
        statement.setObject(4, id);

        int i = statement.executeUpdate();
        System.out.println("Rows updated = " + i);

        bis.close();
        fs.close();
        statement.close();
        connection.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

private static void compressFile(File file, String fileName, ZipOutputStream zipout, String baseDir) {
    try {//from  w ww  .ja  va 2  s. c om
        ZipEntry entry = null;
        if (baseDir.equals("/")) {
            baseDir = "";
        }
        String filename = new String((baseDir + fileName).getBytes(), "GBK");
        entry = new ZipEntry(filename);

        entry.setSize(file.length());
        zipout.putNextEntry(entry);
        BufferedInputStream fr = new BufferedInputStream(new FileInputStream(file));
        int len;
        byte[] buffer = new byte[1024];
        while ((len = fr.read(buffer)) != -1)
            zipout.write(buffer, 0, len);
        fr.close();
    } catch (IOException e) {
    }
}

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

public static void copyFile(InputStream inputStream1, OutputStream outputStream1) throws IOException {

    BufferedInputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    byte[] block = new byte[1024];
    try {//from  w  ww .j a v a 2s . c o  m
        inputStream = new BufferedInputStream(inputStream1);
        outputStream = new BufferedOutputStream(outputStream1);
        while (true) {
            int readLength = inputStream.read(block);
            if (readLength == -1)
                break;// end of file
            outputStream.write(block, 0, readLength);
        }
    } catch (Exception ee) {
        ee.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                log.error("Cannot close stream", ex);
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
                log.error("Cannot close stream", ex);
            }
        }
    }
}

From source file:de.rub.syssec.saaf.analysis.steps.extract.ApkUnzipper.java

/**
 * Extracts the given apk into the given destination directory
 * /*from  w w w . ja va 2 s  .co m*/
 * @param archive
 *            - the file to extract
 * @param dest
 *            - the destination directory
 * @throws IOException
 */
public static void extractApk(File archive, File dest) throws IOException {

    @SuppressWarnings("resource") // Closing it later results in an error
    ZipFile zipFile = new ZipFile(archive);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;

    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();

        String entryFileName = entry.getName();

        byte[] buffer = new byte[16384];
        int len;

        File dir = buildDirectoryHierarchyFor(entryFileName, dest);// destDir
        if (!dir.exists()) {
            dir.mkdirs();
        }

        if (!entry.isDirectory()) {
            if (entry.getSize() == 0) {
                LOGGER.warn("Found ZipEntry \'" + entry.getName() + "\' with size 0 in " + archive.getName()
                        + ". Looks corrupted.");
                continue;
            }

            try {
                bos = new BufferedOutputStream(new FileOutputStream(new File(dest, entryFileName)));// destDir,...

                bis = new BufferedInputStream(zipFile.getInputStream(entry));

                while ((len = bis.read(buffer)) > 0) {
                    bos.write(buffer, 0, len);
                }
                bos.flush();
            } catch (IOException ioe) {
                LOGGER.warn("Failed to extract entry \'" + entry.getName() + "\' from archive. Results for "
                        + archive.getName() + " may not be accurate");
            } finally {
                if (bos != null)
                    bos.close();
                if (bis != null)
                    bis.close();
                // if (zipFile != null) zipFile.close();
            }
        }

    }

}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * ?//from w w w.j  a va 2 s  .  c om
 * 
 * @param files 
 * @param out ?
 * @throws IOException
 * @throws Exception
 */
public static void zipDownLoad(Map<File, String> downQuene, HttpServletResponse response) throws IOException {

    ServletOutputStream out = response.getOutputStream();
    ZipOutputStream zipout = new ZipOutputStream(out);
    ZipEntry entry = null;
    zipout.setLevel(1);
    // zipout.setEncoding("GBK");
    if (downQuene != null && downQuene.size() > 0) {
        for (Entry<File, String> fileInfo : downQuene.entrySet()) {
            File file = fileInfo.getKey();
            try {
                String filename = new String(fileInfo.getValue().getBytes(), "GBK");
                entry = new ZipEntry(filename);
                entry.setSize(file.length());
                zipout.putNextEntry(entry);
            } catch (IOException e) {
                // Logger.getLogger(FileUtil.class).warn(":", e);
            }
            BufferedInputStream fr = new BufferedInputStream(new FileInputStream(fileInfo.getKey()));
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fr.read(buffer)) != -1)
                zipout.write(buffer, 0, len);
            fr.close();
        }
    }

    zipout.finish();
    zipout.flush();
    // out.flush();
}

From source file:gemlite.core.internal.support.hotdeploy.scanner.ScannerIteratorItem.java

private byte[] readContent(ClassLoader loader, JarEntry entry) throws IOException {
    URL url = loader.getResource(entry.getName());
    URLConnection ulc = url.openConnection();
    InputStream in3 = ulc.getInputStream();
    InputStream in2 = url.openStream();

    InputStream in = loader.getResourceAsStream(entry.getName());
    if (in == null) {
        LogUtil.getCoreLog().trace("ReadContent inputStream is null entry.name={} , loader={}", entry.getName(),
                loader);//from  w w  w. ja  v  a  2  s .c  om
    }

    BufferedInputStream bi = new BufferedInputStream(in);
    byte[] bt = new byte[in.available()];
    bi.read(bt);
    bi.close();
    in.close();
    return bt;
}

From source file:com.clouddrive.parth.AmazonOperations.java

public byte[] downloadFile(String fileName, String userName) {
    S3Object object = s3.getObject(new GetObjectRequest(userName, fileName));
    byte[] fileBytes = null;
    try {//from w w w  .j  av  a  2 s  .  co m
        IOUtils.copy(object.getObjectContent(), new FileOutputStream(userName + "" + fileName));

        File file = new File(userName + "" + fileName);

        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream inputStream = new BufferedInputStream(fis);
        fileBytes = new byte[(int) file.length()];
        inputStream.read(fileBytes);
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileBytes;
}

From source file:com.amalto.workbench.compare.CompareManager.java

public String getLeftContent() throws Exception {
    IProject prj = createProject("comparewithsvn");//$NON-NLS-1$
    IFile leftF = prj.getFile("left");//$NON-NLS-1$
    if (!leftF.exists())
        return null;
    byte[] buf = new byte[1024];
    StringBuffer sb = new StringBuffer();
    BufferedInputStream in = new BufferedInputStream(leftF.getContents());
    while (in.read(buf) > 0) {
        sb.append(new String(buf));
        in.read(buf);/*  w  w  w . j a  v  a2  s .  com*/
    }
    return sb.toString().trim();
}