Example usage for java.io BufferedInputStream close

List of usage examples for java.io BufferedInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:org.caboclo.clients.ApiClient.java

protected void downloadURL(String url, File file, Map<String, String> headers)
        throws IllegalStateException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    for (String key : headers.keySet()) {
        String value = headers.get(key);

        httpget.setHeader(key, value);/*from   w  ww .  j  a v a  2  s .c o  m*/
    }

    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            InputStream instream = entity.getContent();
            BufferedInputStream bis = new BufferedInputStream(instream);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            int inByte;
            while ((inByte = bis.read()) != -1) {
                bos.write(inByte);
            }
            bis.close();
            bos.close();
        } catch (IOException ex) {
            throw ex;
        } catch (IllegalStateException ex) {
            httpget.abort();
            throw ex;
        }
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.tesshu.subsonic.client.sample4_music_andmovie.BinaryDownloadApplication.java

@Bean
protected CommandLineRunner run(RestTemplate restTemplate) throws Exception {
    return args -> {

        File tmpDirectory = new File(tmpPath);
        tmpDirectory.mkdir();/*  w w  w  . j  a v a  2 s.  c  o m*/

        Optional<SearchResult2> result2 = search2.getOf("e", null, null, null, null, 1, null, null);
        result2.ifPresent(result -> result.getSongs().forEach(song -> {

            download.download(song, (subject, inputStream) -> {

                File dir = new File(tmpPath + "/" + song.getPath().replaceAll("([^/]+?)?$", StringUtils.EMPTY));
                dir.mkdirs();
                File file = new File(tmpPath + "/" + song.getPath());
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    BufferedInputStream reader = new BufferedInputStream(inputStream);
                    byte buf[] = new byte[256];
                    int len;
                    while ((len = reader.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                    fos.close();
                    reader.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                LOG.info(file.getAbsolutePath());
            }, callback);
        }));

        tmpDirectory.deleteOnExit();
    };

}

From source file:gr.forth.ics.isl.x3mlEditor.upload.UploadReceiver.java

/**
 *
 * @param f//w  ww  .j  a  v a 2 s .  c om
 * @param enc
 * @return
 */
private String readFile(File f, String enc) {
    try {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
        byte[] arr = new byte[(int) f.length()];
        in.read(arr, 0, arr.length);
        in.close();

        return new String(arr, enc);
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        throw new Error("IO Error in readFile");
    }
}

From source file:it.readbeyond.minstrel.librarian.FormatHandlerAbstractZIP.java

protected String getZipEntryText(ZipFile zipFile, ZipEntry ze) {
    String toReturn = "";
    try {//from w  w w.  j a v  a2s  .  c  o m
        BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(ze));
        byte[] bytes = new byte[(int) (ze.getSize())];
        is.read(bytes, 0, bytes.length);
        is.close();
        toReturn = new String(bytes);
    } catch (Exception e) {
        // nothing
    }
    return toReturn;
}

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

public static void copyFile(File org, File des, boolean overwrite) throws IOException {

    if (!org.exists()) {
        throw new FileNotFoundException("Cannot find the source file: " + org.getAbsolutePath());
    }/*from w  w  w .  j  a  v a  2s . c om*/
    if (!org.canRead()) {
        throw new IOException("Cannot read the source file: " + org.getAbsolutePath());
    }

    if (overwrite == false) {
        if (des.exists()) {
            return;
        }
    } else {
        if (des.exists()) {
            if (!des.canWrite()) {
                throw new IOException("Cannot write the destination file: " + des.getAbsolutePath());
            }
        } else {
            if (!des.createNewFile()) {
                throw new IOException("Cannot write the destination file: " + des.getAbsolutePath());
            }
        }
    }

    BufferedInputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    byte[] block = new byte[1024];
    try {
        inputStream = new BufferedInputStream(new FileInputStream(org));
        outputStream = new BufferedOutputStream(new FileOutputStream(des));
        while (true) {
            int readLength = inputStream.read(block);
            if (readLength == -1)
                break;// end of file
            outputStream.write(block, 0, readLength);
        }
    } 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:MainServer.ImageUploadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {//from ww w. j  av a 2 s  . c  o  m
        List<FileItem> items = this.upload.parseRequest(request);
        if (items != null && !items.isEmpty()) {
            for (FileItem item : items) {
                String filename = item.getName();
                String filepath = fileDir + File.separator + filename;
                System.out.println("File path: " + filepath);
                File file = new File(filepath);
                InputStream inputStream = item.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                FileOutputStream fos = new FileOutputStream(file);
                int f;
                while ((f = bis.read()) != -1) {
                    fos.write(f);
                }
                fos.flush();
                fos.close();
                bis.close();
                inputStream.close();
                System.out.println("File: " + filename + "Uploaded");
            }
        }
        System.out.println("Uploaded!");
        out.write("Uploaded!");
    } catch (FileUploadException | IOException e) {
        System.out.println(e);
        out.write(fileDir);
    }
}

From source file:com.sqli.liferay.imex.util.xml.ZipUtils.java

private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {

    if (entry.isDirectory()) {
        createDir(new File(outputDir, entry.getName()));
        return;/*from w ww.  j av a  2s  .c om*/
    }

    File outputFile = new File(outputDir, entry.getName());
    if (!outputFile.getParentFile().exists()) {
        createDir(outputFile.getParentFile());
    }

    log.debug("Extracting: " + entry);
    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

    try {
        IOUtils.copy(inputStream, outputStream);
    } finally {
        outputStream.close();
        inputStream.close();
    }
}

From source file:org.pegadi.webapp.view.FileView.java

protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    // get the file from the map
    File file = (File) map.get("file");

    // check if it exists
    if (file == null || !file.exists() || !file.canRead()) {
        log.warn("Error reading: " + file);
        try {//w w w .  jav a  2 s  . c o m
            response.sendError(404);
        } catch (IOException e) {
            log.error("Could not write to response", e);
        }
        return;
    }
    // give some info in the response
    response.setContentType(getServletContext().getMimeType(file.getAbsolutePath()));
    // files does not change so often, allow three days caching
    response.setHeader("Cache-Control", "max-age=259200");
    response.setContentLength((int) file.length());

    // start writing to the response
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {
        out = new BufferedOutputStream(response.getOutputStream());
        in = new BufferedInputStream(new FileInputStream(file));
        int c = in.read();
        while (c != -1) {
            out.write(c);
            c = in.read();
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

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

public static void copyFile(String srcFilename, String destFilename, boolean overwrite) throws IOException {

    File srcFile = new File(srcFilename);
    if (!srcFile.exists()) {
        throw new FileNotFoundException("Cannot find the source file: " + srcFile.getAbsolutePath());
    }//from  w  w w  . j  a va  2 s.co m
    if (!srcFile.canRead()) {
        throw new IOException("Cannot read the source file: " + srcFile.getAbsolutePath());
    }

    File destFile = new File(destFilename);
    if (overwrite == false) {
        if (destFile.exists()) {
            return;
        }
    } else {
        if (destFile.exists()) {
            if (!destFile.canWrite()) {
                throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
            }
        } else {
            if (!destFile.createNewFile()) {
                throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
            }
        }
    }

    BufferedInputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    byte[] block = new byte[1024];
    try {
        inputStream = new BufferedInputStream(new FileInputStream(srcFile));
        outputStream = new BufferedOutputStream(new FileOutputStream(destFile));
        while (true) {
            int readLength = inputStream.read(block);
            if (readLength == -1)
                break;// end of file
            outputStream.write(block, 0, readLength);
        }
    } 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:com.ottogroup.bi.asap.node.server.AsapProcessingNodeServer.java

/**
 * Reads the contents from the referenced files and returns them as array of bytes
 * @param fileName//from   w w w  .  j  a v  a2 s .  c  o m
 * @return
 * @throws IOException
 */
protected byte[] readFileContents(final String fileName) throws IOException, RequiredInputMissingException {

    if (StringUtils.isBlank(fileName))
        throw new RequiredInputMissingException("Missing required input for parameter 'fileName'");

    ///////////////////////////////////////////////////////////////////////////////////
    // read repo file contents
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
    int read = 0;
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024]; // buffer size
    while ((read = bis.read(buffer)) != -1) {
        os.write(buffer, 0, read);
    }
    bis.close();
    //
    ///////////////////////////////////////////////////////////////////////////////////

    return os.toByteArray();
}