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 synchronized int read(byte b[], int off, int len) throws IOException 

Source Link

Document

Reads bytes from this byte-input stream into the specified byte array, starting at the given offset.

Usage

From source file:com.chinamobile.bcbsp.fault.tools.Zip.java

/**
 * Uncompress *.zip files.//from w ww .  j  a  v  a 2s.  co m
 * @param fileName
 *        : file to be uncompress
 */
@SuppressWarnings("unchecked")
public static void decompress(String fileName) {
    File sourceFile = new File(fileName);
    String filePath = sourceFile.getParent() + "/";
    try {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration en = zipFile.entries();
        byte[] data = new byte[BUFFER];
        while (en.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) en.nextElement();
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(filePath + entry.getName());
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int count;
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                bos.write(data, 0, count);
            }
            bis.close();
            bos.close();
        }
        zipFile.close();
    } catch (IOException e) {
        //LOG.error("[compress]", e);
        throw new RuntimeException("[compress]", e);
    }
}

From source file:com.ibuildapp.romanblack.FanWallPlugin.data.Statics.java

/**
 * download file url and save it/*  w w  w .ja v  a 2 s. co m*/
 *
 * @param url
 */
public static String downloadFile(String url) {
    int BYTE_ARRAY_SIZE = 1024;
    int CONNECTION_TIMEOUT = 30000;
    int READ_TIMEOUT = 30000;

    // downloading cover image and saving it into file
    try {
        URL imageUrl = new URL(URLDecoder.decode(url));
        URLConnection conn = imageUrl.openConnection();
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());

        File resFile = new File(cachePath + File.separator + Utils.md5(url));
        if (!resFile.exists()) {
            resFile.createNewFile();
        }

        FileOutputStream fos = new FileOutputStream(resFile);
        int current = 0;
        byte[] buf = new byte[BYTE_ARRAY_SIZE];
        Arrays.fill(buf, (byte) 0);
        while ((current = bis.read(buf, 0, BYTE_ARRAY_SIZE)) != -1) {
            fos.write(buf, 0, current);
            Arrays.fill(buf, (byte) 0);
        }

        bis.close();
        fos.flush();
        fos.close();
        Log.d("", "");
        return resFile.getAbsolutePath();
    } catch (SocketTimeoutException e) {
        return null;
    } catch (IllegalArgumentException e) {
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:mpimp.assemblxweb.util.J5FileUtils.java

private static void zipDirectoryRecursively(String dirPath, BufferedInputStream origin, int BUFFER,
        ZipOutputStream out, byte[] data, String parentDirName) throws Exception {
    File directory = new File(dirPath);
    File content[] = directory.listFiles();

    for (int i = 0; i < content.length; i++) {
        if (content[i].isDirectory()) {
            String parentPath = parentDirName + File.separator + content[i].getName();
            zipDirectoryRecursively(content[i].getAbsolutePath(), origin, BUFFER, out, data, parentPath);
        } else {//from  ww w.  j a  v a  2  s  . c om
            String filePathInDirectory = parentDirName + File.separator + content[i].getName();
            FileInputStream in = new FileInputStream(content[i].getAbsolutePath());
            origin = new BufferedInputStream(in, BUFFER);
            ZipEntry zipEntry = new ZipEntry(filePathInDirectory);
            out.putNextEntry(zipEntry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
            in.close();
        }
    }
}

From source file:com.seajas.search.contender.scripting.XmlHtmlReader.java

/**
 * Returns the encoding declared in <?xml encoding=...?>, or NULL if none.
 * //from  w  w w.java2s .c o m
 * @param is
 * @param guessedEnc
 * @return String
 * @throws IOException
 */
private static String getXmlProlog(final BufferedInputStream is, final String guessedEnc) {
    try {
        String encoding = null;

        if (guessedEnc != null) {
            byte[] bytes = new byte[BUFFER_SIZE];
            is.mark(BUFFER_SIZE);
            int offset = 0;
            int max = BUFFER_SIZE;
            int c = is.read(bytes, offset, max);
            int firstGT = -1;
            while (c != -1 && firstGT == -1 && offset < BUFFER_SIZE) {
                offset += c;
                max -= c;
                try {
                    c = is.read(bytes, offset, max);
                } catch (IOException e) {
                    if (offset > 0)
                        is.reset();

                    throw e;
                }
                firstGT = new String(bytes, 0, offset).indexOf(">");
            }
            if (firstGT == -1) {
                if (offset > 0)
                    is.reset();
                if (c == -1) {
                    throw new IOException("Unexpected end of XML stream");
                } else {
                    throw new IOException("XML prolog or ROOT element not found on first " + offset + " bytes");
                }
            }
            int bytesRead = offset;
            if (bytesRead > 0) {
                is.reset();
                Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes, 0, firstGT + 1),
                        guessedEnc);
                BufferedReader bReader = new BufferedReader(reader);
                StringBuffer prolog = new StringBuffer();
                String line = bReader.readLine();
                while (line != null) {
                    prolog.append(line);
                    line = bReader.readLine();
                }
                Matcher m = ENCODING_PATTERN.matcher(prolog);
                if (m.find()) {
                    encoding = m.group(1).toUpperCase();
                    encoding = encoding.substring(1, encoding.length() - 1);
                }
            }
        }
        return encoding;
    } catch (IOException e) {
        if (logger.isDebugEnabled())
            logger.debug("Could not retrieve the XML prolog from the given input: " + e.getMessage());

        return null;
    }
}

From source file:com.thejustdo.util.Utils.java

/**
 * Creates a ZIP file containing all the files inside a directory.
 * @param location Directory to read.//from  w w w.  jav  a 2 s  .c o m
 * @param pathname Name and path where to store the file.
 * @throws FileNotFoundException If can't find the initial directory.
 * @throws IOException If can't read/write.
 */
public static void zipDirectory(File location, File pathname) throws FileNotFoundException, IOException {

    BufferedInputStream origin;
    FileOutputStream dest = new FileOutputStream(pathname);
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
    byte data[] = new byte[2048];

    // 1. Get a list of files from current directory
    String files[] = location.list();
    File f;

    // 2. Adding each file to the zip-set.
    for (String s : files) {
        log.info(String.format("Adding: %s", s));
        f = new File(location, s);
        FileInputStream fi = new FileInputStream(f);
        origin = new BufferedInputStream(fi, 2048);
        ZipEntry entry = new ZipEntry(location.getName() + File.separator + s);
        out.putNextEntry(entry);
        int count;
        while ((count = origin.read(data, 0, 2048)) != -1) {
            out.write(data, 0, count);
        }
        origin.close();
    }
    out.close();
}

From source file:com.sun.socialsite.util.Utilities.java

/**
 * Utility method to copy an input stream to an output stream.
 * Wraps both streams in buffers. Ensures right numbers of bytes copied.
 */// w w w  . j  a v  a2  s  . co  m
public static void copyInputToOutput(InputStream input, OutputStream output, long byteCount)
        throws IOException {
    int bytes;
    long length;

    BufferedInputStream in = new BufferedInputStream(input);
    BufferedOutputStream out = new BufferedOutputStream(output);

    byte[] buffer;
    buffer = new byte[8192];

    for (length = byteCount; length > 0;) {
        bytes = (int) (length > 8192 ? 8192 : length);

        try {
            bytes = in.read(buffer, 0, bytes);
        } catch (IOException ex) {
            try {
                in.close();
                out.close();
            } catch (IOException ex1) {
            }
            throw new IOException("Reading input stream, " + ex.getMessage());
        }

        if (bytes < 0)
            break;

        length -= bytes;

        try {
            out.write(buffer, 0, bytes);
        } catch (IOException ex) {
            try {
                in.close();
                out.close();
            } catch (IOException ex1) {
            }
            throw new IOException("Writing output stream, " + ex.getMessage());
        }
    }

    try {
        in.close();
        out.close();
    } catch (IOException ex) {
        throw new IOException("Closing file streams, " + ex.getMessage());
    }
}

From source file:com.sun.faces.generate.RenderKitSpecificationGenerator.java

public static void copyResourceToFile(String resourceName, File file) throws Exception {
    FileOutputStream fos = null;/*from   w w  w. j a va 2  s .co m*/
    BufferedInputStream bis = null;
    URL url = null;
    URLConnection conn = null;
    byte[] bytes = new byte[1024];
    int len = 0;

    fos = new FileOutputStream(file);
    url = getCurrentLoader(fos).getResource(resourceName);
    conn = url.openConnection();
    conn.setUseCaches(false);
    bis = new BufferedInputStream(conn.getInputStream());
    while (-1 != (len = bis.read(bytes, 0, 1024))) {
        fos.write(bytes, 0, len);
    }
    fos.close();
    bis.close();

}

From source file:piramide.multimodal.downloader.client.RestClient.java

private String[] json2list(String url) throws DownloaderException {
    try {/*from   w w w.  j  a  va2 s .  c  om*/
        final HttpClient client = new DefaultHttpClient();
        final HttpResponse response = client.execute(new HttpGet(url));
        final InputStream is = response.getEntity().getContent();
        final int size = (int) response.getEntity().getContentLength();
        final byte[] buffer = new byte[size];
        final BufferedInputStream bis = new BufferedInputStream(is);
        int position = 0;
        while (position < size) {
            final int read = bis.read(buffer, position, buffer.length - position);
            if (read <= 0)
                break;
            position += read;
        }

        final String strResponse = new String(buffer);
        final JSONArray arr = new JSONArray(strResponse);
        final String[] returnValue = new String[arr.length()];

        for (int i = 0; i < arr.length(); ++i)
            returnValue[i] = arr.getString(i);

        return returnValue;
    } catch (ClientProtocolException e) {
        throw new DownloaderException(e.getMessage(), e);
    } catch (IllegalStateException e) {
        throw new DownloaderException(e.getMessage(), e);
    } catch (IOException e) {
        throw new DownloaderException(e.getMessage(), e);
    } catch (JSONException e) {
        throw new DownloaderException(e.getMessage(), e);
    }
}

From source file:it.geosolutions.tools.compress.file.Extractor.java

public static void unZip(File inputZipFile, File outputDir) throws IOException, CompressorException {
    if (inputZipFile == null || outputDir == null) {
        throw new CompressorException("Unzip: with null parameters");
    }/*from w  w  w.j  ava 2  s .  com*/

    if (!outputDir.exists()) {
        if (!outputDir.mkdirs()) {
            throw new CompressorException("Unzip: Unable to create directory structure: " + outputDir);
        }
    }

    final int BUFFER = Conf.getBufferSize();

    ZipInputStream zipInputStream = null;
    try {
        // Open Zip file for reading
        zipInputStream = new ZipInputStream(new FileInputStream(inputZipFile));
    } catch (FileNotFoundException fnf) {
        throw new CompressorException("Unzip: Unable to find the input zip file named: " + inputZipFile);
    }

    // extract file if not a directory
    BufferedInputStream bis = new BufferedInputStream(zipInputStream);
    // grab a zip file entry
    ZipEntry entry = null;
    while ((entry = zipInputStream.getNextEntry()) != null) {
        // Process each entry

        File currentFile = new File(outputDir, entry.getName());

        FileOutputStream fos = null;
        BufferedOutputStream dest = null;
        try {
            int currentByte;
            // establish buffer for writing file
            byte data[] = new byte[BUFFER];

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

            // read and write until last byte is encountered
            while ((currentByte = bis.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, currentByte);
            }
        } catch (IOException ioe) {

        } finally {
            try {
                if (dest != null) {
                    dest.flush();
                    dest.close();
                }
                if (fos != null)
                    fos.close();
            } catch (IOException ioe) {
                throw new CompressorException(
                        "Unzip: unable to close the zipInputStream: " + ioe.getLocalizedMessage());
            }
        }
    }
    try {
        if (zipInputStream != null)
            zipInputStream.close();
    } catch (IOException ioe) {
        throw new CompressorException(
                "Unzip: unable to close the zipInputStream: " + ioe.getLocalizedMessage());
    }
    try {
        if (bis != null)
            bis.close();
    } catch (IOException ioe) {
        throw new CompressorException(
                "Unzip: unable to close the Buffered zipInputStream: " + ioe.getLocalizedMessage());
    }
}

From source file:piramide.multimodal.client.tester.ApplicationDownloader.java

private void downloadFile(HttpResponse response, OutputStream os) throws IOException {
    final InputStream is = response.getEntity().getContent();
    long size = response.getEntity().getContentLength();
    BufferedInputStream bis = new BufferedInputStream(is);
    final byte[] buffer = new byte[1024 * 1024]; // 1 MB
    long position = 0;
    while (position < size) {
        final int read = bis.read(buffer, 0, buffer.length);
        if (read <= 0)
            break;

        os.write(buffer, 0, read);//from ww  w  .j  ava  2 s . c  o  m
        os.flush();

        position += read;
    }
    is.close();
}