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:com.ibm.amc.resources.TemporaryFileResource.java

/**
 * Write an InputStream to a local file//ww  w  . j av  a2s .  co  m
 * 
 * @param stream
 *            contains the file
 * @return a File object from the input stream
 * @throws IOException
 */
private File writeToFile(InputStream stream) throws IOException {
    if (logger.isEntryEnabled())
        logger.entry("writeToFile", stream);
    File file = FileManager.createUploadFile();

    BufferedInputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(stream);
        out = new BufferedOutputStream(new FileOutputStream(file));

        IOUtils.copy(in, out);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error("ERROR: IOException thrown attempting to close the input stream", e);
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.error("ERROR: IOException thrown attempting to close the output stream", e);
            }
        }
    }
    if (logger.isEntryEnabled())
        logger.exit("writeToFile", file);
    return file;
}

From source file:edu.harvard.i2b2.eclipse.plugins.metadataLoader.util.FileUtil.java

public static void unZipAll(File source, File destination) throws IOException {
    System.out.println("Unzipping - " + source.getName());
    int BUFFER = 2048;

    ZipFile zip = new ZipFile(source);
    try {/*from   ww  w.  j ava2s.  co  m*/
        destination.getParentFile().mkdirs();
        Enumeration zipFileEntries = zip.entries();

        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            File destFile = new File(destination, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            File destinationParent = destFile.getParentFile();

            // create the parent directory structure if needed
            destinationParent.mkdirs();

            if (!entry.isDirectory()) {
                BufferedInputStream is = null;
                FileOutputStream fos = null;
                BufferedOutputStream dest = null;
                try {
                    is = new BufferedInputStream(zip.getInputStream(entry));
                    int currentByte;
                    // establish buffer for writing file
                    byte data[] = new byte[BUFFER];

                    // write the current file to disk
                    fos = new FileOutputStream(destFile);
                    dest = new BufferedOutputStream(fos, BUFFER);

                    // read and write until last byte is encountered
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, currentByte);
                    }
                } catch (Exception e) {
                    System.out.println("unable to extract entry:" + entry.getName());
                    throw e;
                } finally {
                    if (dest != null) {
                        dest.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                }
            } else {
                //Create directory
                destFile.mkdirs();
            }

            if (currentEntry.endsWith(".zip")) {
                // found a zip file, try to extract
                unZipAll(destFile, destinationParent);
                if (!destFile.delete()) {
                    System.out.println("Could not delete zip");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Failed to successfully unzip:" + source.getName());
    } finally {
        zip.close();
    }
    System.out.println("Done Unzipping:" + source.getName());
}

From source file:com.annuletconsulting.homecommand.node.AsyncSend.java

@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
    AsyncTaskLoader<String> loader = new AsyncTaskLoader<String>(activity) {
        @Override//w  w w.jav a2 s .  c om
        public String loadInBackground() {
            StringBuffer instr = new StringBuffer();
            try {
                Socket connection = new Socket(ipAddr, port);
                BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
                OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
                osw.write(formatJSON(command.toUpperCase()));
                osw.write(13);
                osw.flush();
                BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
                InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
                int c;
                while ((c = isr.read()) != 13)
                    instr.append((char) c);
                isr.close();
                bis.close();
                osw.close();
                bos.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return instr.toString();
        }
    };
    return loader;
}

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * GZipping a string.//  w w w .  j  a v a2  s  .c  o  m
 * 
 * @param data the content to be gzipped.
 * @param filename the name for the file.
 * @return a ByteArrayDataSource.
 */
protected ByteArrayDataSource compressFile(File fileName) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gz = new GZIPOutputStream(out);
    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(fileName));
    byte[] dataBuffer = new byte[512];
    while ((bufferedInputStream.read(dataBuffer)) != -1) {
        gz.write(dataBuffer);
    }
    gz.close();
    bufferedInputStream.close();
    ByteArrayDataSource dataSrc = new ByteArrayDataSource(out.toByteArray(), "application/x-gzip");
    return dataSrc;
}

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 w w  w. java2  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:averroes.JarFile.java

/**
 * Add the given file with the given entry name to this JAR file.
 * //from  w  w w  . ja  v a2 s . c o  m
 * @param source
 * @param entryName
 * @throws IOException
 */
public void add(File source, String entryName) throws IOException {
    JarEntry entry = new JarEntry(entryName);
    entry.setTime(source.lastModified());
    getJarOutputStream().putNextEntry(entry);
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));

    byte[] buffer = new byte[1024];
    int len;
    while ((len = in.read(buffer)) != -1) {
        getJarOutputStream().write(buffer, 0, len);
    }
    getJarOutputStream().closeEntry();
    in.close();
}

From source file:jeffaschenk.tomcat.instance.generator.builders.TomcatInstanceBuilderHelper.java

/**
 * Pull specified Version of Tomcat from Internet Download Site ...
 *
 * @param GENERATION_LOGGER Logger/*  w  w  w  .ja v  a2s  .  c o  m*/
 * @param tomcatInstance    POJO
 */
protected static boolean pullTomcatVersionFromApacheMirror(GenerationLogger GENERATION_LOGGER,
        TomcatAvailableArchives tomcatAvailableArchives, TomcatInstance tomcatInstance) {
    /**
     * First determine the Latest Release based upon our Short name.
     */
    TomcatArchive tomcatArchive = tomcatAvailableArchives
            .getAvailableArchiveByShortName(tomcatInstance.getTomcatVersion());
    if (tomcatArchive == null || tomcatArchive.getShortVersion() == null) {
        GENERATION_LOGGER.error("Unable to determine a Download Archive for Tomcat Version: "
                + tomcatInstance.getTomcatVersion() + ", Notify Engineering to Support new Version of Tomcat!");
        return false;
    }
    tomcatInstance.setTomcatArchive(tomcatArchive); // Set a Reference to archive used.
    /**
     * Now check to see if the Artifact has already been pulled?
     */
    if (validateTomcatDownloadedVersion(GENERATION_LOGGER, tomcatInstance, false)) {
        GENERATION_LOGGER.info("Using previously Downloaded Archive: " + tomcatArchive.getName() + ".zip");
        return true;
    }
    /**
     * Proceed to Pull Archive ...
     */
    GENERATION_LOGGER.info("Pulling Tomcat Version from Apache Mirror ...");

    URL url = null;
    URLConnection con = null;
    int i;
    try {
        /**
         * Construct the Apache Mirror URL to Pull Tomcat Instance.
         * Assume a V8 version ...
         */
        String tcHeadVersion;
        if (tomcatInstance.getTomcatVersion().startsWith("v8")) {
            tcHeadVersion = DefaultDefinitions.APACHE_TOMCAT_8_MIRROR_HEAD;
        } else if (tomcatInstance.getTomcatVersion().startsWith("v9")) {
            tcHeadVersion = DefaultDefinitions.APACHE_TOMCAT_9_MIRROR_HEAD;
        } else {
            GENERATION_LOGGER.error("Unable to determine a Download URL for Tomcat Version: "
                    + tomcatInstance.getTomcatVersion()
                    + ", Notify Engineering to Support new Version of Tomcat!");
            return false;
        }
        /**
         * Now construct the URL to use to Pull over Internet.
         */
        url = new URL(tomcatAvailableArchives.getApacheMirrorHeadUrl() + "/" + tcHeadVersion + "/v"
                + tomcatArchive.getShortVersion() + "/bin/" + tomcatArchive.getName() + ".zip");
        GENERATION_LOGGER.info("Using URL for Downloading Artifact: " + url.toString());

        con = url.openConnection();
        BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(tomcatInstance.getDestinationFolder().getAbsolutePath() + File.separator
                        + tomcatArchive.getName() + ".zip"));
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.flush();
        bis.close();
        GENERATION_LOGGER.info("Successfully Pulled Tomcat Version from Apache Mirror ...");
        return true;
    } catch (MalformedInputException malformedInputException) {
        malformedInputException.printStackTrace();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
    /**
     * Indicate a Failure has Occurred
     */
    return false;
}

From source file:com.slytechs.capture.StreamFactory.java

public <T extends InputCapture<? extends FilePacket>> T newInput(final Class<T> t, final File file,
        Filter<ProtocolFilterTarget> filter) throws IOException {

    final BufferedInputStream b = new BufferedInputStream(new FileInputStream(file));
    b.mark(1024); // Buffer first 1K of stream so we can rewind

    /*/*from   ww  w.j  ava 2 s  . co  m*/
     * Check the stream, without decompression first
     */
    if (formatType(Channels.newChannel(b)) != null) {
        b.close();

        /*
         * This is a plain uncompressed file, open up a FileChannel. It will be
         * much faster
         */
        return newInput(t, new RandomAccessFile(file, "rw").getChannel(), filter);
    }

    /*
     * Try with gunziped stream, second
     */
    b.reset(); // Rewind
    if (formatType(Channels.newChannel(new GZIPInputStream(b))) != null) {
        b.close();

        /*
         * Now reopen the same file, but this time without the buffered
         * inputstream in the middle. Try to make things as efficient as possible.
         * TODO: implement much faster channel based GZIP decompression algorithm
         */
        return newInput(t, Channels.newChannel(new GZIPInputStream(new FileInputStream(file))), filter);
    }

    throw new IllegalArgumentException(
            "File is not any compressed or decompressed known format [" + file.getName() + "]");

}

From source file:com.slytechs.capture.StreamFactory.java

public InputCapture<? extends CapturePacket> newInput(final File file,
        final Filter<ProtocolFilterTarget> filter) throws IOException {

    final BufferedInputStream b = new BufferedInputStream(new FileInputStream(file));
    b.mark(1024); // Buffer first 1K of stream so we can rewind

    /*/*  w  ww  . ja  v  a2 s .c om*/
     * Check the stream, without decompression first
     */
    if (formatType(Channels.newChannel(b)) != null) {
        b.close();

        /*
         * This is a plain uncompressed file, open up a FileChannel. It will be
         * much faster
         */
        return newInput(new RandomAccessFile(file, "rw").getChannel(), filter);
    }

    /*
     * Try with gunziped stream, second
     */
    b.reset(); // Rewind
    if (formatType(Channels.newChannel(new GZIPInputStream(b))) != null) {
        b.close();

        /*
         * Now reopen the same file, but this time without the buffered
         * inputstream in the middle. Try to make things as efficient as possible.
         * TODO: implement much faster channel based GZIP decompression algorithm
         */
        return newInput(Channels.newChannel(new GZIPInputStream(new FileInputStream(file))), filter);
    }

    b.close();
    return factoryForOther.getFactory().newInput(new RandomAccessFile(file, "r").getChannel(), filter);

}

From source file:fr.mby.opa.picsimpl.service.BasicPictureFactory.java

@Override
public Picture build(final String filename, final byte[] contents)
        throws IOException, PictureAlreadyExistsException, UnsupportedPictureTypeException {
    Assert.hasText(filename, "No filename supplied !");
    Assert.notNull(contents, "No contents supplied !");

    Picture picture = null;//from w  ww . j  ava2 s .  c  om
    if (contents.length > 0) {
        picture = new Picture();

        picture.setFilename(filename);
        picture.setName(filename);

        final BufferedInputStream bufferedStream = new BufferedInputStream(new ByteArrayInputStream(contents),
                contents.length);
        bufferedStream.mark(contents.length + 1);

        this.loadPicture(picture, contents, bufferedStream);

        this.loadMetadata(picture, bufferedStream);

        bufferedStream.close();
    }

    return picture;
}