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.viettel.dms.download.DownloadFile.java

/**
 * Copy from one stream to another.  Throws IOException in the event of error
 * (for example, SD card is full)//from   w  ww  . j  a va 2  s .  c  om
 * 
 * @param is         Input stream.
 * @param os         Output stream.
 * @param buffer      Temporary buffer to use for copy.
 * @param bufferSize   Size of temporary buffer, in bytes.
 */
public static void copyStream(BufferedInputStream is, BufferedOutputStream os, byte[] buffer, int bufferSize)
        throws IOException {
    int sizeDownloaded = 0;
    int percent = 0;
    try {
        for (;;) {
            int count = is.read(buffer, 0, bufferSize);
            if (count >= 0) {
                sizeDownloaded += count;
                percent = (int) ((float) (sizeDownloaded) / (float) (fileSize) * 100);
                VTLog.d("copyStream", "current count: " + count + " sizeDownloaded: " + sizeDownloaded
                        + " fileSize: " + fileSize + " percent: " + percent);
                if (percent > 98) {
                    percent = 98;
                }
                try {
                    Context ct = GlobalInfo.getInstance().getActivityContext();
                    if (ct != null && ct instanceof GlobalBaseActivity) {
                        ((GlobalBaseActivity) ct).updateProgressPercentDialog(percent);
                    }
                } catch (Exception e) {
                    VTLog.e("copyStream", "fail", e);
                }
            }
            if (count == -1) {
                break;
            }
            os.write(buffer, 0, count);
        }
        os.flush();
    } catch (IOException e) {
        throw e;
    }
}

From source file:com.yoctopuce.YoctoAPI.YFirmwareUpdate.java

static byte[] _downloadfile(String url) throws YAPI_Exception {
    ByteArrayOutputStream result = new ByteArrayOutputStream(1024);
    URL u = null;//from   ww w  .  j av  a2s  . co  m
    try {
        u = new URL(url);
    } catch (MalformedURLException e) {
        throw new YAPI_Exception(YAPI.IO_ERROR, e.getLocalizedMessage());
    }
    BufferedInputStream in = null;
    try {
        URLConnection connection = u.openConnection();
        in = new BufferedInputStream(connection.getInputStream());
        byte[] buffer = new byte[1024];
        int readed = 0;
        while (readed >= 0) {
            readed = in.read(buffer, 0, buffer.length);
            if (readed < 0) {
                // end of connection
                break;
            } else {
                result.write(buffer, 0, readed);
            }
        }

    } catch (IOException e) {
        throw new YAPI_Exception(YAPI.IO_ERROR,
                "unable to contact www.yoctopuce.com :" + e.getLocalizedMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignore) {
            }
        }
    }
    return result.toByteArray();
}

From source file:fr.landel.utils.io.InternalFileSystemUtils.java

/**
 * Copy a file.//w w  w  .j  a  v a 2 s .  c o  m
 * 
 * @param src
 *            The source file name
 * @param dest
 *            The destination file name
 * @param removeSource
 *            Remove the source after copy
 * @throws IOException
 *             Exception thrown if problems occurs during coping
 */
protected static void copyFile(final File src, final File dest, final boolean removeSource) throws IOException {
    int bufferReadSize;
    final byte[] buffer = new byte[BUFFER_SIZE];

    final File target;
    if (dest.isDirectory()) {
        target = new File(dest, src.getName());
    } else {
        target = dest;
    }

    if (InternalFileSystemUtils.createDirectory(target.getParentFile())) {
        if (!src.getAbsolutePath().equals(dest.getAbsolutePath())) {
            final BufferedInputStream bis = IOStreamUtils.createBufferedInputStream(src);
            final BufferedOutputStream bos = IOStreamUtils.createBufferedOutputStream(target);

            while ((bufferReadSize = bis.read(buffer, 0, BUFFER_SIZE)) >= 0) {
                bos.write(buffer, 0, bufferReadSize);
            }

            CloseableManager.close(target);
            CloseableManager.close(src);

            if (removeSource && !src.delete()) {
                throw new IOException("Cannot remove the source file");
            }
        }
    } else {
        throw new FileNotFoundException("destination directory doesn't exist and cannot be created");
    }
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.imageloader.Utils.java

public static String downloadFile(Context context, String url, String md5) {
    final int BYTE_ARRAY_SIZE = 8024;
    final int CONNECTION_TIMEOUT = 30000;
    final int READ_TIMEOUT = 30000;

    try {/*from w w w.j  a v a  2s . co  m*/
        for (int i = 0; i < 3; i++) {
            URL fileUrl = new URL(URLDecoder.decode(url));
            HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.connect();

            int status = connection.getResponseCode();

            if (status >= HttpStatus.SC_BAD_REQUEST) {
                connection.disconnect();

                continue;
            }

            BufferedInputStream bufferedInputStream = new BufferedInputStream(connection.getInputStream());
            File file = new File(StaticData.getCachePath(context) + md5);

            if (!file.exists()) {
                new File(StaticData.getCachePath(context)).mkdirs();
                file.createNewFile();
            }

            FileOutputStream fileOutputStream = new FileOutputStream(file, false);
            int byteCount;
            byte[] buffer = new byte[BYTE_ARRAY_SIZE];

            while ((byteCount = bufferedInputStream.read(buffer, 0, BYTE_ARRAY_SIZE)) != -1)
                fileOutputStream.write(buffer, 0, byteCount);

            bufferedInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();

            return file.getAbsolutePath();
        }
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

    return null;
}

From source file:net.amigocraft.mpt.util.MiscUtil.java

public static boolean unzip(ZipFile zip, File dest, List<String> files) throws MPTException {
    boolean returnValue = true;
    try {//w  w  w. j av  a2  s . com
        List<String> existingDirs = new ArrayList<>();
        Enumeration<? extends ZipEntry> en = zip.entries();
        entryLoop: while (en.hasMoreElements()) {
            ZipEntry entry = en.nextElement();
            String name = entry.getName().startsWith("./")
                    ? entry.getName().substring(2, entry.getName().length())
                    : entry.getName();
            File file = new File(dest, name);
            if (entry.isDirectory()) {
                if (file.exists()) {
                    if (DISALLOW_MERGE) {
                        existingDirs.add(name);
                        if (VERBOSE)
                            Main.log.warning("Refusing to extract directory " + name + ": already exists");
                    }
                }
            } else {
                files.add(name);
                for (String dir : DISALLOWED_DIRECTORIES) {
                    if (file.getPath().startsWith(dir)) {
                        if (VERBOSE)
                            Main.log.warning("Refusing to extract " + name + " from " + zip.getName()
                                    + ": parent directory \"" + dir + "\" is not allowed");
                        continue entryLoop;
                    }
                }
                if (DISALLOW_MERGE) {
                    for (String dir : existingDirs) {
                        if (file.getPath().substring(2, file.getPath().length()).replace(File.separator, "/")
                                .startsWith(dir)) {
                            continue entryLoop;
                        }
                    }
                }
                if (!DISALLOW_OVERWRITE || !file.exists()) {
                    file.getParentFile().mkdirs();
                    for (String ext : DISALLOWED_EXTENSIONS) {
                        if (file.getName().endsWith(ext)) {
                            if (VERBOSE)
                                Main.log.warning("Refusing to extract " + name + " from " + zip.getName()
                                        + ": extension \"" + ext + "\" is not allowed");
                            returnValue = false;
                            continue entryLoop;
                        }
                    }
                    BufferedInputStream bIs = new BufferedInputStream(zip.getInputStream(entry));
                    int b;
                    byte[] buffer = new byte[1024];
                    FileOutputStream fOs = new FileOutputStream(file);
                    BufferedOutputStream bOs = new BufferedOutputStream(fOs, 1024);
                    while ((b = bIs.read(buffer, 0, 1024)) != -1)
                        bOs.write(buffer, 0, b);
                    bOs.flush();
                    bOs.close();
                    bIs.close();
                } else {
                    if (VERBOSE)
                        Main.log.warning(
                                "Refusing to extract " + name + " from " + zip.getName() + ": already exists");
                    returnValue = false;
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace(); //TODO
        throw new MPTException(ERROR_COLOR + "Failed to extract archive!");
    }
    return returnValue;
}

From source file:info.varden.anatychia.Main.java

public static MaterialDataList materialList(SaveData save, ProgressUpdater pu, MaterialData[] filters) {
    Random random = new Random();
    boolean filtersNull = filters == null;
    pu.updated(0, 1);//from ww  w  . j  a v a  2s. co m
    pu.updated(-3, 1);
    MaterialDataList mdl = new MaterialDataList();
    File saveDir = save.getLocation();
    File[] regionFolders = listRegionContainers(saveDir);
    int depth = Integer.MAX_VALUE;
    File shallowest = null;
    for (File f : regionFolders) {
        String path = f.getAbsolutePath();
        Pattern p = Pattern.compile(Pattern.quote(File.separator));
        Matcher m = p.matcher(path);
        int count = 0;
        while (m.find()) {
            count++;
        }
        if (count < depth) {
            depth = count;
            if (shallowest == null || f.getName().equalsIgnoreCase("region")) {
                shallowest = f;
            }
        }
    }
    pu.updated(-1, 1);
    ArrayList<File> regions = new ArrayList<File>();
    int tfs = 0;
    for (File f : regionFolders) {
        String dimName = f.getParentFile().getName();
        boolean deleted = false;
        if (f.equals(shallowest)) {
            dimName = "DIM0";
        }
        if (!filtersNull) {
            for (MaterialData type : filters) {
                if (type.getType() == MaterialType.DIMENSION && type.getName().equals(dimName)) {
                    System.out.println("Deleting: " + dimName);
                    deleted = recursiveDelete(f);
                }
            }
        }
        if (deleted)
            continue;
        mdl.increment(new MaterialData(MaterialType.DIMENSION, dimName, 1L));
        File[] r = f.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".mca");
            }

        });
        int max = r.length;
        int cur = 0;
        for (File valid : r) {
            cur++;
            try {
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(valid));
                byte[] offsetHeader = new byte[4096];
                bis.read(offsetHeader, 0, 4096);
                bis.close();
                ByteBuffer bb = ByteBuffer.wrap(offsetHeader);
                IntBuffer ib = bb.asIntBuffer();
                while (ib.remaining() > 0) {
                    if (ib.get() != 0) {
                        tfs++;
                    }
                }
                bb = null;
                ib = null;
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            // tfs += Math.floor(valid.length() / 1000D);
            pu.updated(cur, max);
        }
        regions.addAll(Arrays.asList(r));
    }
    if (regions.size() <= 0) {
        pu.updated(1, 1);
        return mdl;
    }
    pu.updated(-2, 1);
    int fc = 0;
    int fs = 0;
    for (File region : regions) {
        fc++;
        //fs += Math.floor(region.length() / 1000D);
        try {
            RegionFile anvil = new RegionFile(region);
            for (int x = 0; x < 32; x++) {
                for (int z = 0; z < 32; z++) {
                    InputStream is = anvil.getChunkDataInputStream(x, z);
                    if (is == null)
                        continue;
                    NBTInputStream nbti = new NBTInputStream(is, CompressionMode.NONE);
                    CompoundTag root = (CompoundTag) nbti.readTag();
                    String rootName = root.getName();
                    CompoundTag level = (CompoundTag) root.getValue().get("Level");
                    Map<String, Tag> levelTags = level.getValue();
                    ListTag sectionTag = (ListTag) levelTags.get("Sections");
                    ArrayList<Tag> sections = new ArrayList<Tag>(sectionTag.getValue());
                    for (int i = 0; i < sections.size(); i++) {
                        mdl.setSectorsRelative(1);
                        CompoundTag sect = (CompoundTag) sections.get(i);
                        Map<String, Tag> sectTags = sect.getValue();
                        ByteArrayTag blockArray = (ByteArrayTag) sectTags.get("Blocks");
                        byte[] add = new byte[0];
                        boolean hasAdd = false;
                        if (sectTags.containsKey("Add")) {
                            hasAdd = true;
                            ByteArrayTag addArray = (ByteArrayTag) sectTags.get("Add");
                            add = addArray.getValue();
                        }
                        byte[] blocks = blockArray.getValue();
                        for (int j = 0; j < blocks.length; j++) {
                            short id;
                            byte aid = (byte) 0;
                            if (hasAdd) {
                                aid = ChunkFormat.Nibble4(add, j);
                                id = (short) ((blocks[j] & 0xFF) + (aid << 8));
                            } else {
                                id = (short) (blocks[j] & 0xFF);
                            }
                            if (!filtersNull) {
                                for (MaterialData type : filters) {
                                    if (type.getType() == MaterialType.BLOCK
                                            && type.getName().equals(String.valueOf(blocks[j] & 0xFF))
                                            && (type.getRemovalChance() == 1D
                                                    || random.nextDouble() < type.getRemovalChance())) {
                                        blocks[j] = (byte) 0;
                                        if (aid != 0) {
                                            add[j / 2] = (byte) (add[j / 2] & (j % 2 == 0 ? 0xF0 : 0x0F));
                                        }
                                        id = (short) 0;
                                    }
                                }
                            }
                            mdl.increment(new MaterialData(MaterialType.BLOCK, String.valueOf(id), 1L));
                        }
                        if (!filtersNull) {
                            HashMap<String, Tag> rSectTags = new HashMap<String, Tag>();
                            rSectTags.putAll(sectTags);
                            ByteArrayTag bat = new ByteArrayTag("Blocks", blocks);
                            rSectTags.put("Blocks", bat);
                            if (hasAdd) {
                                ByteArrayTag adt = new ByteArrayTag("Add", add);
                                rSectTags.put("Add", adt);
                            }
                            CompoundTag rSect = new CompoundTag(sect.getName(), rSectTags);
                            sections.set(i, rSect);
                        }
                    }
                    ListTag entitiesTag = (ListTag) levelTags.get("Entities");
                    ArrayList<Tag> entities = new ArrayList<Tag>(entitiesTag.getValue());
                    for (int i = entities.size() - 1; i >= 0; i--) {
                        CompoundTag entity = (CompoundTag) entities.get(i);
                        Map<String, Tag> entityTags = entity.getValue();
                        if (entityTags.containsKey("id")) {
                            StringTag idTag = (StringTag) entityTags.get("id");
                            String id = idTag.getValue();
                            boolean removed = false;
                            if (!filtersNull) {
                                for (MaterialData type : filters) {
                                    if (type.getType() == MaterialType.ENTITY
                                            && (type.getName().equals(id) || type.getName().equals(""))
                                            && (type.getRemovalChance() == 1D
                                                    || random.nextDouble() < type.getRemovalChance())) {
                                        if (type.fulfillsRequirements(entity)) {
                                            entities.remove(i);
                                            removed = true;
                                        }
                                    }
                                }
                            }
                            if (!removed) {
                                mdl.increment(new MaterialData(MaterialType.ENTITY, id, 1L));
                            }
                        }
                    }
                    nbti.close();
                    is.close();
                    if (!filtersNull) {
                        HashMap<String, Tag> rLevelTags = new HashMap<String, Tag>();
                        rLevelTags.putAll(levelTags);
                        ListTag rSectionTag = new ListTag("Sections", CompoundTag.class, sections);
                        rLevelTags.put("Sections", rSectionTag);
                        ListTag rEntityTag = new ListTag("Entities", CompoundTag.class, entities);
                        rLevelTags.put("Entities", rEntityTag);
                        final CompoundTag rLevel = new CompoundTag("Level", rLevelTags);
                        HashMap<String, Tag> rRootTags = new HashMap<String, Tag>() {
                            {
                                put("Level", rLevel);
                            }
                        };
                        CompoundTag rRoot = new CompoundTag(rootName, rRootTags);
                        OutputStream os = anvil.getChunkDataOutputStream(x, z);
                        NBTOutputStream nbto = new NBTOutputStream(os, CompressionMode.NONE);
                        nbto.writeTag(rRoot);
                        nbto.close();
                    }
                    fs++;
                    pu.updated(fs, tfs);
                }
            }
            anvil.close();
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    MaterialData[] data = mdl.toArray();
    System.out.println("FILES SCANNED: " + fc);
    for (MaterialData d : data) {
        System.out.println(d.getType().getName() + ": " + d.getName() + " (" + d.getQuantity() + ")");
    }
    return mdl;
}

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

/**
 * Compress files to *.zip.//w w w. j av  a  2s. com
 * @param fileName
 *        file name to compress
 * @return compressed file.
 */
public static String compress(String fileName) {
    String targetFile = null;
    File sourceFile = new File(fileName);
    Vector<File> vector = getAllFiles(sourceFile);
    try {
        if (sourceFile.isDirectory()) {
            targetFile = fileName + ".zip";
        } else {
            char ch = '.';
            targetFile = fileName.substring(0, fileName.lastIndexOf(ch)) + ".zip";
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile));
        ZipOutputStream zipos = new ZipOutputStream(bos);
        byte[] data = new byte[BUFFER];
        if (vector.size() > 0) {
            for (int i = 0; i < vector.size(); i++) {
                File file = vector.get(i);
                zipos.putNextEntry(new ZipEntry(getEntryName(fileName, file)));
                bis = new BufferedInputStream(new FileInputStream(file));
                int count;
                while ((count = bis.read(data, 0, BUFFER)) != -1) {
                    zipos.write(data, 0, count);
                }
                bis.close();
                zipos.closeEntry();
            }
            zipos.close();
            bos.close();
            return targetFile;
        } else {
            File zipNullfile = new File(targetFile);
            zipNullfile.getParentFile().mkdirs();
            zipNullfile.mkdir();
            return zipNullfile.getAbsolutePath();
        }
    } catch (IOException e) {
        LOG.error("[compress]", e);
        return "error";
    }
}

From source file:com.seleniumtests.util.FileUtility.java

public static void extractJar(final String storeLocation, final Class<?> clz) throws IOException {
    File firefoxProfile = new File(storeLocation);
    String location = clz.getProtectionDomain().getCodeSource().getLocation().getFile();

    try (JarFile jar = new JarFile(location);) {
        logger.info("Extracting jar file::: " + location);
        firefoxProfile.mkdir();//www .j  a  v  a  2s . co  m

        Enumeration<?> jarFiles = jar.entries();
        while (jarFiles.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) jarFiles.nextElement();
            String currentEntry = entry.getName();
            File destinationFile = new File(storeLocation, currentEntry);
            File destinationParent = destinationFile.getParentFile();

            // create the parent directory structure if required
            destinationParent.mkdirs();
            if (!entry.isDirectory()) {
                BufferedInputStream is = new BufferedInputStream(jar.getInputStream(entry));
                int currentByte;

                // buffer for writing file
                byte[] data = new byte[BUFFER];

                // write the current file to disk
                try (FileOutputStream fos = new FileOutputStream(destinationFile);) {
                    BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);

                    // read and write till last byte
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        destination.write(data, 0, currentByte);
                    }

                    destination.flush();
                    destination.close();
                    is.close();
                }
            }
        }
    }

    FileUtils.deleteDirectory(new File(storeLocation + "\\META-INF"));
    if (OSUtility.isWindows()) {
        new File(storeLocation + "\\" + clz.getCanonicalName().replaceAll("\\.", "\\\\") + ".class").delete();
    } else {
        new File(storeLocation + "/" + clz.getCanonicalName().replaceAll("\\.", "/") + ".class").delete();
    }
}

From source file:com.ibm.amc.FileManager.java

public static File decompress(URI temporaryFileUri) {
    final File destination = new File(getUploadDirectory(), temporaryFileUri.getSchemeSpecificPart());
    if (!destination.mkdirs()) {
        throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR, "CWZBA2001E_DIRECTORY_CREATION_FAILED",
                destination.getPath());// www  .ja v  a  2s  .c  o  m
    }

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(getFileForUri(temporaryFileUri));

        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File newDirOrFile = new File(destination, entry.getName());
            if (newDirOrFile.getParentFile() != null && !newDirOrFile.getParentFile().exists()) {
                if (!newDirOrFile.getParentFile().mkdirs()) {
                    throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR,
                            "CWZBA2001E_DIRECTORY_CREATION_FAILED", newDirOrFile.getParentFile().getPath());
                }
            }
            if (entry.isDirectory()) {
                if (!newDirOrFile.mkdir()) {
                    throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR,
                            "CWZBA2001E_DIRECTORY_CREATION_FAILED", newDirOrFile.getPath());
                }
            } else {
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int size;
                byte[] buffer = new byte[ZIP_BUFFER];
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newDirOrFile),
                        ZIP_BUFFER);
                while ((size = bis.read(buffer, 0, ZIP_BUFFER)) != -1) {
                    bos.write(buffer, 0, size);
                }
                bos.flush();
                bos.close();
                bis.close();
            }
        }
    } catch (Exception e) {
        throw new AmcRuntimeException(e);
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                logger.debug("decompress", "close failed with " + e);
            }
        }
    }

    return destination;
}

From source file:Main.java

/**
 * Zips a subfolder/*  w  w  w.j a  v  a2  s .  c  o  m*/
 */
protected static void zipSubFolder(ZipOutputStream zipOut, File srcFolder, int basePathLength)
        throws IOException {
    final int BUFFER = 2048;

    File[] fileList = srcFolder.listFiles();
    BufferedInputStream bis = null;

    for (File file : fileList) {

        if (file.isDirectory()) {
            zipSubFolder(zipOut, file, basePathLength);

        } else {
            byte data[] = new byte[BUFFER];
            String unmodifiedFilePath = file.getPath();
            String relativePath = unmodifiedFilePath.substring(basePathLength);
            Log.d("ZIP SUBFOLDER", "Relative Path : " + relativePath);

            FileInputStream fis = new FileInputStream(unmodifiedFilePath);
            bis = new BufferedInputStream(fis, BUFFER);

            ZipEntry zipEntry = new ZipEntry(relativePath);
            zipOut.putNextEntry(zipEntry);

            int count;
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                zipOut.write(data, 0, count);
            }

            bis.close();
        }
    }
}