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:eu.learnpad.simulator.mon.utils.Manager.java

/**
 * It reads text from file and provides it on string
 *     * /*from w w  w  .  j  a  v  a  2 s  . co  m*/
 * @param filePath the file to read path
 * @return a String containing all the file text
 */
@SuppressWarnings("deprecation")
public static String ReadTextFromFile(String filePath) {
    File file = new File(filePath);
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    DataInputStream dis = null;
    StringBuilder strB = new StringBuilder();

    try {
        fis = new FileInputStream(file);

        // Here BufferedInputStream is added for fast reading.
        bis = new BufferedInputStream(fis);
        dis = new DataInputStream(bis);

        while (dis.available() != 0) {
            // this statement reads the line from the file and print it to
            // the console.
            strB.append(dis.readLine());

        }
        // dispose all the resources after using them.
        fis.close();
        bis.close();
        dis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return strB.toString();
}

From source file:modnlp.capte.AlignerUtils.java

@SuppressWarnings("deprecation")
/* This method creates the HTTP connection to the server 
 * and sends the POST request with the two files for alignment,
 * // w  w w. ja  v  a 2  s .c om
 * The server returns the aligned file as the response to the post request, 
 * which is delimited by the tag <beginalignment> which separates the file
 * from the rest of the POST request
 * 
 * 
 * 
 */
public static String MultiPartFileUpload(String source, String target) throws IOException {
    String response = "";
    String serverline = System.getProperty("capte.align.server"); //"http://ronaldo.cs.tcd.ie:80/~gplynch/aling.cgi";   
    PostMethod filePost = new PostMethod(serverline);
    // Send any XML file as the body of the POST request
    File f1 = new File(source);
    File f2 = new File(target);
    System.out.println(f1.getName());
    System.out.println(f2.getName());
    System.out.println("File1 Length = " + f1.length());
    System.out.println("File2 Length = " + f2.length());
    Part[] parts = {

            new StringPart("param_name", "value"), new FilePart(f2.getName(), f2),
            new FilePart(f1.getName(), f1) };
    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    HttpClient client = new HttpClient();
    int status = client.executeMethod(filePost);
    String res = "";
    InputStream is = filePost.getResponseBodyAsStream();
    Header[] heads = filePost.getResponseHeaders();
    Header[] feet = filePost.getResponseFooters();
    BufferedInputStream bis = new BufferedInputStream(is);

    String datastr = null;
    StringBuffer sb = new StringBuffer();
    byte[] bytes = new byte[8192]; // reading as chunk of 8192
    int count = bis.read(bytes);
    while (count != -1 && count <= 8192) {
        datastr = new String(bytes, "UTF8");

        sb.append(datastr);
        count = bis.read(bytes);
    }

    bis.close();
    res = sb.toString();

    System.out.println("----------------------------------------");
    System.out.println("Status is:" + status);
    //System.out.println(res);
    /* for debugging
    for(int i = 0 ;i < heads.length ;i++){
      System.out.println(heads[i].toString());
                   
    }
    for(int j = 0 ;j < feet.length ;j++){
      System.out.println(feet[j].toString());
                   
    }
    */
    filePost.releaseConnection();
    String[] handle = res.split("<beginalignment>");
    //Check for errors in the header
    // System.out.println(handle[0]);
    //Return the required text
    String ho = "";
    if (handle.length < 2) {
        System.out.println("Server error during alignment, check file encodings");
        ho = "error";
    } else {
        ho = handle[1];
    }
    return ho;

}

From source file:Main.java

public static void copyFile(File oldLocation, File newLocation) throws IOException {
    if (oldLocation.exists()) {
        BufferedInputStream reader = new BufferedInputStream(new FileInputStream(oldLocation));
        BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(newLocation, false));
        try {/*from www  .j  a  va 2s. c  o  m*/
            byte[] buff = new byte[8192];
            int numChars;
            while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
                writer.write(buff, 0, numChars);
            }
        } catch (IOException ex) {
            throw new IOException(
                    "IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
        } finally {
            try {
                if (reader != null) {
                    writer.close();
                    reader.close();
                }
            } catch (IOException ex) {
                Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to "
                        + newLocation.getPath());
            }
        }
    } else {
        throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to "
                + newLocation.getPath());
    }
}

From source file:Main.java

public static boolean bitmapToOutPutStream(final Bitmap bitmap, OutputStream outputStream) {

    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {// w  ww.ja va 2s  .  c o m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());

        in = new BufferedInputStream(inputStream, 8 * 1024);
        out = new BufferedOutputStream(outputStream, 8 * 1024);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}

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 w  ww.ja v a 2 s .  c o 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:de.lazyzero.kkMulticopterFlashTool.utils.Zip.java

public static void unzip2folder(File zipFile, File toFolder) throws FileExistsException {
    if (!toFolder.exists()) {
        toFolder.mkdirs();//from  w w  w.j  av  a 2  s . co m
    } else if (toFolder.isFile()) {
        throw new FileExistsException(toFolder.getName());
    }

    try {
        ZipEntry entry;
        @SuppressWarnings("resource")
        ZipFile zipfile = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> e = zipfile.entries();
        while (e.hasMoreElements()) {
            entry = e.nextElement();

            //            String newDir;
            //            if (entry.getName().indexOf("/") == -1) {
            //               newDir = zipFile.getName().substring(0, zipFile.getName().indexOf("."));
            //            } else {
            //               newDir = entry.getName().substring(0, entry.getName().indexOf("/"));
            //            }
            //            String folder = toFolder + (File.separatorChar+"") + newDir;
            //            System.out.println(folder);
            //            if ((new File(folder).mkdir())) {
            //               System.out.println("Done.");
            //            }
            System.out.println("Extracting: " + entry);
            if (entry.isDirectory()) {
                new File(toFolder + (File.separatorChar + "") + entry.getName()).mkdir();
            } else {
                BufferedInputStream is = new BufferedInputStream(zipfile.getInputStream(entry));
                int count;
                byte data[] = new byte[2048];
                String fileName = toFolder + (File.separatorChar + "") + entry.getName();
                FileOutputStream fos = new FileOutputStream(fileName);
                BufferedOutputStream dest = new BufferedOutputStream(fos, 2048);
                while ((count = is.read(data, 0, 2048)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
                is.close();
                System.out.println("extracted to: " + fileName);
            }

        }
    } catch (ZipException e1) {
        zipFile.delete();
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {

    }

}

From source file:com.glaf.core.util.ZipUtils.java

private static void recurseFiles(JarOutputStream jos, File file, String s)
        throws IOException, FileNotFoundException {

    if (file.isDirectory()) {
        s = s + file.getName() + "/";
        jos.putNextEntry(new JarEntry(s));
        String as[] = file.list();
        if (as != null) {
            for (int i = 0; i < as.length; i++)
                recurseFiles(jos, new File(file, as[i]), s);
        }//w  ww  .j  av a2s.  c  o  m
    } else {
        if (file.getName().endsWith("MANIFEST.MF") || file.getName().endsWith("META-INF/MANIFEST.MF")) {
            return;
        }
        JarEntry jarentry = new JarEntry(s + file.getName());
        FileInputStream fileinputstream = new FileInputStream(file);
        BufferedInputStream bufferedinputstream = new BufferedInputStream(fileinputstream);
        jos.putNextEntry(jarentry);
        while ((len = bufferedinputstream.read(buf)) >= 0) {
            jos.write(buf, 0, len);
        }
        bufferedinputstream.close();
        jos.closeEntry();
    }
}

From source file:Main.java

private static void zipFile(ZipOutputStream zipOutputStream, String sourcePath) throws IOException {

    java.io.File files = new java.io.File(sourcePath);
    java.io.File[] fileList = files.listFiles();

    String entryPath = "";
    BufferedInputStream input = null;
    for (java.io.File file : fileList) {
        if (file.isDirectory()) {
            zipFile(zipOutputStream, file.getPath());
        } else {//from   w ww  .  j  av  a  2 s .c  om
            byte data[] = new byte[BUFFER_SIZE];
            FileInputStream fileInputStream = new FileInputStream(file.getPath());
            input = new BufferedInputStream(fileInputStream, BUFFER_SIZE);
            entryPath = file.getAbsolutePath().replace(parentPath, "");

            ZipEntry entry = new ZipEntry(entryPath);
            zipOutputStream.putNextEntry(entry);

            int count;
            while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
                zipOutputStream.write(data, 0, count);
            }
            input.close();
        }
    }

}

From source file:com.byraphaelmedeiros.autosubdown.AutoSubDown.java

private static void downloadTo(Rule rule, String link) {
    LOGGER.log(Level.INFO, "Downloading " + link + "...");

    try {/* w ww . j a v a  2 s .c  o  m*/
        String extension = FilenameUtils.getExtension(link);
        BufferedInputStream bis = new BufferedInputStream(new URL(link).openStream());
        FileOutputStream fos = new FileOutputStream(
                rule.getDownloadTo() + File.separator + rule.getFileName() + "." + extension);
        BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

        byte data[] = new byte[1024];
        int x = 0;

        while ((x = bis.read(data, 0, 1024)) >= 0) {
            bos.write(data, 0, x);
        }

        bos.close();
        bis.close();
    } catch (MalformedURLException e) {
        //e.printStackTrace();
        LOGGER.log(Level.WARNING, "Invalid URL! (" + link + ")");
    } catch (IOException e) {
        //e.printStackTrace();
        LOGGER.log(Level.WARNING, "Unable to access the URL (" + link + ").");
    }
}

From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java

public static void saveFile(String foldername, String filename, InputStream input) throws IOException {

    // LogWriter log = LogWriter.getInstance();

    if (filename == null) {
        filename = File.createTempFile("xx", ".out").getName(); //$NON-NLS-1$ //$NON-NLS-2$
    }// w  w w  .  ja v a2  s  . c  o  m
    // Do no overwrite existing file
    File file = new File(foldername, filename);
    for (int i = 0; file.exists(); i++) {
        file = new File(foldername, filename + i);
    }
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    BufferedInputStream bis = new BufferedInputStream(input);
    int aByte;
    while ((aByte = bis.read()) != -1) {
        bos.write(aByte);
    }

    bos.flush();
    bos.close();
    bis.close();
}