Example usage for java.io BufferedOutputStream close

List of usage examples for java.io BufferedOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

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

Usage

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

@Override
public void start(Stage stage) throws Exception {

    Search2Controller search2 = context.getBean(Search2Controller.class);

    StreamController streamController = context.getBean(StreamController.class);

    SuccessObserver callback = context.getBean(SuccessObserver.class);

    File tmpDirectory = new File(tmpPath);
    tmpDirectory.mkdir();/*from   www . 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 -> {
        Optional<Child> maybeSong = result.getSongs().stream().findFirst();
        maybeSong.ifPresent(song -> {

            streamController.stream(song, maxBitRate, format, null, null, null, null,
                    (subject, inputStream, contentLength) -> {

                        File dir = new File(
                                tmpPath + "/" + song.getPath().replaceAll("([^/]+?)?$", StringUtils.EMPTY));
                        dir.mkdirs();

                        File file = new File(tmpPath + "/"
                                + song.getPath().replaceAll("([^.]+?)?$", StringUtils.EMPTY) + format);

                        try {
                            BufferedOutputStream fos = new BufferedOutputStream(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();
                        }

                        String path = Paths.get(file.getPath()).toUri().toString();
                        Group root = new Group();
                        Scene scene = new Scene(root, 640, 480);
                        Media media = new Media(path);
                        MediaPlayer player = new MediaPlayer(media);
                        MediaView view = new MediaView(player);
                        ((Group) scene.getRoot()).getChildren().add(view);
                        stage.setScene(scene);
                        stage.show();

                        player.play();

                    }, callback);

        });

    });
}

From source file:dictinsight.utils.io.HttpUtils.java

/**
 * https??post/*from   w  w  w. ja  v  a2  s.co m*/
 * @param url
 * @param param
 * @return post?
 */
public static String httpsPostData(String url, String param) {
    class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    BufferedOutputStream brOutStream = null;
    BufferedReader reader = null;

    try {
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        HttpsURLConnection connection = (HttpsURLConnection) (new URL(url)).openConnection();
        connection.setSSLSocketFactory(context.getSocketFactory());
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Proxy-Connection", "Keep-Alive");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(1000 * 15);

        brOutStream = new BufferedOutputStream(connection.getOutputStream());
        brOutStream.write(param.getBytes());
        brOutStream.flush();

        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String responseContent = "";
        String line = reader.readLine();
        while (line != null) {
            responseContent += line;
            line = reader.readLine();
        }

        return responseContent;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (brOutStream != null)
                brOutStream.close();
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileSelector.java

protected File unzip3(File zf) throws FileNotFoundException {
    //File f = null;
    String rename = zf.getAbsolutePath().replaceFirst("\\.zip", identifier + ".xml");//.replaceFirst("\\.gz", ".xml");
    File f = new File(rename);
    try {//w w  w .  j  a v  a 2 s  .c  o  m
        FileInputStream fis = new FileInputStream(zf);

        ZipInputStream zin = new ZipInputStream(fis);
        ZipEntry ze;

        final byte[] content = new byte[BUFFER];

        while ((ze = zin.getNextEntry()) != null) {
            f = new File(getCalTempPath() + File.separator + ze.getName());
            FileOutputStream fos = new FileOutputStream(f);
            BufferedOutputStream bos = new BufferedOutputStream(fos, content.length);

            int n = 0;
            while (-1 != (n = zin.read(content))) {
                bos.write(content, 0, n);
            }
            bos.flush();
            bos.close();
        }

        fis.close();
        zin.close();
    } catch (IOException ioe) {
        jlog.error("Error processing Zip " + zf + " Excluding! :: " + ioe);
        return null;
    }
    //try again... what could go wrong
    /*
    if (checkMinFileSize(f) && retry_counter<MAX_UNGZIP_RETRIES){
       retry_counter++;
       f.delete();
       f = unzip2(zf);
    }
    */
    return f;
}

From source file:com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.TarExtractor.java

private void extractEntry(@NonNull final Context context, TarArchiveInputStream inputStream,
        TarArchiveEntry entry, String outputDir) throws IOException {
    File outputFile = new File(outputDir, fixEntryName(entry.getName()));

    if (!outputFile.getCanonicalPath().startsWith(outputDir)) {
        throw new IOException("Incorrect TarArchiveEntry path!");
    }//from   w  w w . ja va  2  s  .c o m

    if (entry.isDirectory()) {
        FileUtil.mkdir(outputFile, context);
        return;
    }

    if (!outputFile.getParentFile().exists()) {
        FileUtil.mkdir(outputFile.getParentFile(), context);
    }

    BufferedOutputStream outputStream = new BufferedOutputStream(FileUtil.getOutputStream(outputFile, context));
    try {
        int len;
        byte buf[] = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
        while ((len = inputStream.read(buf)) != -1) {
            if (!listener.isCancelled()) {
                outputStream.write(buf, 0, len);
                ServiceWatcherUtil.position += len;
            } else
                break;
        }
    } finally {
        outputStream.close();
    }
}

From source file:com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.GzipExtractor.java

private void extractEntry(@NonNull final Context context, TarArchiveInputStream inputStream,
        TarArchiveEntry entry, String outputDir) throws IOException {

    File outputFile = new File(outputDir, fixEntryName(entry.getName()));
    if (!outputFile.getCanonicalPath().startsWith(outputDir)) {
        throw new IOException("Incorrect ZipEntry path!");
    }//  w w  w  .  ja  va  2s . c  om

    if (entry.isDirectory()) {
        FileUtil.mkdir(outputFile, context);
        return;
    }

    if (!outputFile.getParentFile().exists()) {
        FileUtil.mkdir(outputFile.getParentFile(), context);
    }

    BufferedOutputStream outputStream = new BufferedOutputStream(FileUtil.getOutputStream(outputFile, context));
    try {
        int len;
        byte buf[] = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
        while ((len = inputStream.read(buf)) != -1) {
            if (!listener.isCancelled()) {
                outputStream.write(buf, 0, len);
                ServiceWatcherUtil.position += len;
            } else
                break;
        }
    } finally {
        outputStream.close();
    }
}

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

/**
 * Extracts the given apk into the given destination directory
 * /*w ww .j  av a2s  .  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:it.smartcommunitylab.climb.domain.controller.ChildController.java

@RequestMapping(value = "/api/child/image/upload/png/{ownerId}/{objectId}", method = RequestMethod.POST)
public @ResponseBody String uploadImage(@RequestParam("file") MultipartFile file, @PathVariable String ownerId,
        @PathVariable String objectId, HttpServletRequest request) throws Exception {
    Criteria criteria = Criteria.where("objectId").is(objectId);
    Child child = storage.findOneData(Child.class, criteria, ownerId);
    if (child == null) {
        throw new EntityNotFoundException("child not found");
    }//from   ww  w. ja v a  2s.  co  m
    if (!validateAuthorization(ownerId, child.getInstituteId(), child.getSchoolId(), null, null,
            Const.AUTH_RES_Image, Const.AUTH_ACTION_ADD, request)) {
        throw new UnauthorizedException("Unauthorized Exception: token not valid");
    }
    String name = objectId + ".png";
    if (logger.isInfoEnabled()) {
        logger.info("uploadImage:" + name);
    }
    if (!file.isEmpty()) {
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File(imageUploadDir + "/" + name)));
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
    }
    return "{\"status\":\"OK\"}";
}

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 .  java 2  s .c  o m*/
    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:com.glaf.report.jxls.JxlsReportContainer.java

public byte[] toXls(String reportId, String actorId, Map<String, Object> context) {
    Workbook wb = JxlsReportContainer.getContainer().execute(reportId, actorId, context);
    if (wb != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        try {// ww  w.j a v a  2s . c o m
            wb.write(bos);
            bos.flush();
            return baos.toByteArray();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            wb = null;
            try {
                baos.close();
            } catch (IOException e) {
            }
            try {
                bos.close();
            } catch (IOException e) {
            }
            baos = null;
            bos = null;
        }
    }
    return null;
}

From source file:com.nabla.dc.server.ImageService.java

private boolean exportImage(final String imageId, final HttpServletResponse response)
        throws IOException, SQLException, InternalErrorException {
    final Connection conn = db.getConnection();
    try {/*from   www .  ja va  2  s .  c om*/
        final PreparedStatement stmt = StatementFormat.prepare(conn, "SELECT * FROM image WHERE id=?;",
                imageId);
        try {
            final ResultSet rs = stmt.executeQuery();
            try {
                if (!rs.next()) {
                    if (log.isDebugEnabled())
                        log.debug("failed to find report ID= " + imageId);
                    return false;
                }
                if (log.isTraceEnabled())
                    log.trace("exporting image " + imageId);
                response.reset();
                response.setBufferSize(DEFAULT_BUFFER_SIZE);
                response.setContentType(rs.getString("content_type"));
                response.setHeader("Content-Length", String.valueOf(rs.getInt("length")));
                response.setHeader("Content-Disposition",
                        MessageFormat.format("inline; filename=\"{0}\"", rs.getString("name")));
                // to prevent images to be downloaded every time user hovers one image
                final Calendar cal = Calendar.getInstance();
                cal.setTime(new Date());
                cal.add(Calendar.MONTH, 2);
                response.setDateHeader("Expires", cal.getTime().getTime());
                final BufferedInputStream input = new BufferedInputStream(rs.getBinaryStream("content"),
                        DEFAULT_BUFFER_SIZE);
                try {
                    final BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(),
                            DEFAULT_BUFFER_SIZE);
                    try {
                        final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                        int length;
                        while ((length = input.read(buffer)) > 0)
                            output.write(buffer, 0, length);
                    } finally {
                        output.close();
                    }
                } finally {
                    input.close();
                }
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
    } finally {
        conn.close();
    }
    return true;
}