Example usage for java.io BufferedInputStream BufferedInputStream

List of usage examples for java.io BufferedInputStream BufferedInputStream

Introduction

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

Prototype

public BufferedInputStream(InputStream in) 

Source Link

Document

Creates a BufferedInputStream and saves its argument, the input stream in, for later use.

Usage

From source file:com.twemyeez.picklr.InstallManager.java

public static void unzip() {

    // Firstly get the working directory
    String workingDirectory = Minecraft.getMinecraft().mcDataDir.getAbsolutePath();

    // If it ends with a . then remove it
    if (workingDirectory.endsWith(".")) {
        workingDirectory = workingDirectory.substring(0, workingDirectory.length() - 1);
    }// ww  w .j  a  va2  s.  c  om

    // If it doesn't end with a / then add it
    if (!workingDirectory.endsWith("/") && !workingDirectory.endsWith("\\")) {
        workingDirectory = workingDirectory + "/";
    }

    // Use a test file to see if libraries installed
    File file = new File(workingDirectory + "mods/mp3spi1.9.5.jar");

    // If the libraries are installed, return
    if (file.exists()) {
        System.out.println("Checking " + file.getAbsolutePath());
        System.out.println("Target file exists, so not downloading API");
        return;
    }

    // Now try to download the libraries
    try {

        String location = "http://www.javazoom.net/mp3spi/sources/mp3spi1.9.5.zip";

        // Define the URL
        URL url = new URL(location);

        // Get the ZipInputStream
        ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream((url).openStream()));

        // Use a temporary ZipEntry as a buffer
        ZipEntry zipFile;

        // While there are more file entries
        while ((zipFile = zipInput.getNextEntry()) != null) {
            // Check if it is one of the file names that we want to copy
            Boolean required = false;
            if (zipFile.getName().indexOf("mp3spi1.9.5.jar") != -1) {
                required = true;
            }
            if (zipFile.getName().indexOf("jl1.0.1.jar") != -1) {
                required = true;
            }
            if (zipFile.getName().indexOf("tritonus_share.jar") != -1) {
                required = true;
            }
            if (zipFile.getName().indexOf("LICENSE.txt") != -1) {
                required = true;
            }

            // If it is, then we shall now copy it
            if (!zipFile.getName().replace("MpegAudioSPI1.9.5/", "").equals("") && required) {

                // Get the file location
                String tempFile = new File(zipFile.getName()).getName();

                tempFile = tempFile.replace("LICENSE.txt", "MpegAudioLicence.txt");

                // Initialise the target file
                File targetFile = (new File(
                        workingDirectory + "mods/" + tempFile.replace("MpegAudioSPI1.9.5/", "")));

                // Print a debug/alert message
                System.out.println("Picklr is extracting to " + workingDirectory + "mods/"
                        + tempFile.replace("MpegAudioSPI1.9.5/", ""));

                // Make parent directories if required
                targetFile.getParentFile().mkdirs();

                // If the file does not exist, create it
                if (!targetFile.exists()) {
                    targetFile.createNewFile();
                }

                // Create a buffered output stream to the destination
                BufferedOutputStream destinationOutput = new BufferedOutputStream(
                        new FileOutputStream(targetFile, false), 2048);

                // Store the data read
                int bytesRead;

                // Data buffer
                byte dataBuffer[] = new byte[2048];

                // While there is still data to write
                while ((bytesRead = zipInput.read(dataBuffer, 0, 2048)) != -1) {
                    // Write it to the output stream
                    destinationOutput.write(dataBuffer, 0, bytesRead);
                }

                // Flush the output
                destinationOutput.flush();

                // Close the output stream
                destinationOutput.close();
            }

        }
        // Close the zip input
        zipInput.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.lushapp.common.web.utils.DownloadUtils.java

public static void download(HttpServletRequest request, HttpServletResponse response, String filePath,
        String displayName) throws IOException {
    File file = new File(filePath);

    if (StringUtils.isEmpty(displayName)) {
        displayName = file.getName();//from  w ww.  j ava2  s . c om
    }

    if (!file.exists() || !file.canRead()) {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("??");
        return;
    }

    response.reset();
    WebUtils.setNoCacheHeader(response);

    response.setContentType("application/x-download");
    response.setContentLength((int) file.length());

    String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    displayFilename = displayFilename.replace(" ", "_");
    WebUtils.setDownloadableHeader(request, response, displayFilename);
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(new FileInputStream(file));
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.milaboratory.util.CompressionType.java

private static InputStream createInputStream(CompressionType ct, InputStream is) throws IOException {
    switch (ct) {
    case None://from w ww.ja v  a  2 s  .c  om
        return is;
    case GZIP:
        return new GZIPInputStream(is, 2048);
    case BZIP2:
        CompressorStreamFactory factory = new CompressorStreamFactory();
        try {
            return factory.createCompressorInputStream(CompressorStreamFactory.BZIP2,
                    new BufferedInputStream(is));
        } catch (CompressorException e) {
            throw new IOException(e);
        }
    }
    throw new NullPointerException();
}

From source file:de.thischwa.pmcms.server.ServletUtils.java

public static boolean writeFile(HttpServletResponse resp, File reqFile) {
    boolean retVal = false;
    InputStream in = null;/*  w  w w  .  j  av  a 2s. c om*/
    try {
        in = new BufferedInputStream(new FileInputStream(reqFile));
        IOUtils.copy(in, resp.getOutputStream());
        logger.debug("File successful written to servlet response: " + reqFile.getAbsolutePath());
    } catch (FileNotFoundException e) {
        logger.error("Resource not found: " + reqFile.getAbsolutePath());
    } catch (IOException e) {
        logger.error(String.format("Error while rendering [%s]: %s", reqFile.getAbsolutePath(), e.getMessage()),
                e);
    } finally {
        IOUtils.closeQuietly(in);
    }
    return retVal;
}

From source file:Main.java

/** Obtiene el flujo de entrada de un fichero (para su lectura) a partir de su URI.
 * @param uri URI del fichero a leer//from   www.ja  v  a  2 s .c  o m
 * @return Flujo de entrada hacia el contenido del fichero
 * @throws IOException Cuando no se ha podido abrir el fichero de datos. */
public static InputStream loadFile(final URI uri) throws IOException {

    if (uri == null) {
        throw new IllegalArgumentException("Se ha pedido el contenido de una URI nula"); //$NON-NLS-1$
    }

    if (uri.getScheme().equals("file")) { //$NON-NLS-1$
        // Es un fichero en disco. Las URL de Java no soportan file://, con
        // lo que hay que diferenciarlo a mano

        // Retiramos el "file://" de la uri
        String path = uri.getSchemeSpecificPart();
        if (path.startsWith("//")) { //$NON-NLS-1$
            path = path.substring(2);
        }
        return new FileInputStream(new File(path));
    }

    // Es una URL
    final InputStream tmpStream = new BufferedInputStream(uri.toURL().openStream());

    // Las firmas via URL fallan en la descarga por temas de Sun, asi que
    // descargamos primero
    // y devolvemos un Stream contra un array de bytes
    final byte[] tmpBuffer = getDataFromInputStream(tmpStream);

    return new java.io.ByteArrayInputStream(tmpBuffer);
}

From source file:Main.java

public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws IOException {
    HttpURLConnection urlConnection = null;
    try {/*from   w w w . ja v a  2 s.  c  o m*/
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.api.dao.ZipUtils.java

/**
 * check if the {@link InputStream} provided is a zip file
 * /*from w  ww .  j  a  v a2 s  .c om*/
 * @param in the stream.
 * @return if it is a ZIP file.
 */
public static boolean isZipStream(InputStream in) {
    if (!in.markSupported()) {
        in = new BufferedInputStream(in);
    }
    boolean isZip = true;
    try {
        in.mark(MAGIC.length);
        for (byte element : MAGIC) {
            if (element != (byte) in.read()) {
                isZip = false;
                break;
            }
        }
        in.reset();
    } catch (IOException e) {
        isZip = false;
    }
    return isZip;
}

From source file:Main.java

/**
 * Downloads a file via HTTP(S) GET to the given path. This function cannot be called from the
 * UI thread. Android does not allow it.
 *
 * @param urlString Url to the ressource to download.
 * @param file      file to be written to.
 * @param overwrite if file exists, overwrite?
 * @return flase if download was not successful. If successful, true.
 *///from ww  w .java  2  s .c  o m
private static Boolean fileDownloadHttp(String urlString, File file, Boolean overwrite) {
    HashMap<String, String> result = null;
    URL url = null;
    //        File temp;

    try {
        url = new URL(urlString);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setReadTimeout(200000);
        urlConnection.connect();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        FileOutputStream outputStream = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = in.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }

        in.close();
        outputStream.close();
        urlConnection.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    Log.d(TAG, "File download: " + file.getAbsolutePath() + url.getFile() + "overwrite " + overwrite
            + "exists? " + file.exists());
    return true;
}

From source file:com.threerings.cast.bundle.tools.ComponentBundlerUtil.java

/**
 * Parses the action tileset definitions in the supplied file and puts them into a hash map,
 * keyed on action name.//w w w. j a va2s .c  o  m
 */
public static Map<String, TileSet> parseActionTileSets(File file) throws IOException, SAXException {
    return parseActionTileSets(new BufferedInputStream(new FileInputStream(file)));
}

From source file:Main.java

/**
 * Compare the contents of two Streams to determine if they are equal or
 * not.// www  . j  av a2 s  .co  m
 * <p/>
 * This method buffers the input internally using
 * <code>BufferedInputStream</code> if they are not already buffered.
 *
 * @param input1 the first stream
 * @param input2 the second stream
 * @return true if the content of the streams are equal or they both don't
 * exist, false otherwise
 * @throws NullPointerException if either input is null
 * @throws IOException  if an I/O error occurs
 */
public static boolean contentEquals(InputStream input1, InputStream input2) throws IOException {
    if (!(input1 instanceof BufferedInputStream)) {
        input1 = new BufferedInputStream(input1);
    }
    if (!(input2 instanceof BufferedInputStream)) {
        input2 = new BufferedInputStream(input2);
    }

    int ch = input1.read();
    while (EOF != ch) {
        int ch2 = input2.read();
        if (ch != ch2) {
            return false;
        }
        ch = input1.read();
    }

    int ch2 = input2.read();
    return ch2 == EOF;
}