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:de.tudarmstadt.ukp.csniper.resbuild.stuff.BncCheckDocuments.java

public static void main(String[] args) throws IOException {
    boolean enabled = false;

    for (File f : FileUtils.listFiles(new File(BASE), new String[] { "xml" }, true)) {
        BufferedInputStream bis = null;
        try {//from  www . j a  v  a  2  s. c  om
            bis = new BufferedInputStream(new FileInputStream(f));
            int c;
            StringBuilder sb = new StringBuilder();
            while ((c = bis.read()) != '>') {
                if (enabled) {
                    if (c == '"') {
                        enabled = false;
                        break;
                    } else {
                        sb.append((char) c);
                    }
                }
                if (c == '"') {
                    enabled = true;
                }
            }
            String name = f.getName().substring(0, 3);
            String id = sb.toString();
            if (!name.equals(id)) {
                System.out.println("Name is [" + name + "], but ID is [" + id + "].");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(bis);
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws IOException {
    FileOutputStream f = new FileOutputStream("test.zip");
    CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
    ZipOutputStream zos = new ZipOutputStream(csum);
    BufferedOutputStream out = new BufferedOutputStream(zos);
    zos.setComment("A test of Java Zipping");

    for (int i = 0; i < args.length; i++) {
        System.out.println("Writing file " + args[i]);
        BufferedReader in = new BufferedReader(new FileReader(args[i]));
        zos.putNextEntry(new ZipEntry(args[i]));
        int c;//from   ww  w .j a va2 s . c  om
        while ((c = in.read()) != -1)
            out.write(c);
        in.close();
    }
    out.close();

    System.out.println("Checksum: " + csum.getChecksum().getValue());

    System.out.println("Reading file");
    FileInputStream fi = new FileInputStream("test.zip");
    CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
    ZipInputStream in2 = new ZipInputStream(csumi);
    BufferedInputStream bis = new BufferedInputStream(in2);
    ZipEntry ze;
    while ((ze = in2.getNextEntry()) != null) {
        System.out.println("Reading file " + ze);
        int x;
        while ((x = bis.read()) != -1)
            System.out.write(x);
    }
    System.out.println("Checksum: " + csumi.getChecksum().getValue());
    bis.close();

}

From source file:Data.java

public static void main(String[] args) {
    Data data = new Data(1);
    try {//from www  .j  a v a 2s .co m
        ObjectOutputStream objectOut = new ObjectOutputStream(
                new BufferedOutputStream(new FileOutputStream("C:/test.bin")));
        objectOut.writeObject(data);
        System.out.println("1st Object written has value: " + data.getValue());
        data.setValue(2);
        objectOut.writeObject(data);
        System.out.println("2nd Object written has value: " + data.getValue());
        data.setValue(3);
        objectOut.writeObject(data);
        System.out.println("3rd Object written has value: " + data.getValue());
        objectOut.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    try {
        ObjectInputStream objectIn = new ObjectInputStream(
                new BufferedInputStream(new FileInputStream("C:/test.bin")));
        Data data1 = (Data) objectIn.readObject();
        Data data2 = (Data) objectIn.readObject();
        Data data3 = (Data) objectIn.readObject();
        System.out.println(data1.equals(data2));
        System.out.println(data2.equals(data3));
        System.out.println(data1.getValue());
        System.out.println(data2.getValue());
        System.out.println(data3.getValue());
        objectIn.close();
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:edu.msu.cme.rdp.taxatree.TreeBuilder.java

public static void main(String[] args) throws IOException {
    if (args.length != 3) {
        System.err.println("USAGE: TreeBuilder <idmapping> <merges.bin> <newick_out>");
        return;/*from   w  w  w.ja va2 s . co  m*/
    }

    IdMapping<Integer> idMapping = IdMapping.fromFile(new File(args[0]));
    DataInputStream mergeStream = new DataInputStream(new BufferedInputStream(new FileInputStream(args[1])));
    TaxonHolder lastMerged = null;
    int taxid = 0;
    final Map<Integer, Double> distMap = new HashMap();
    Map<Integer, TaxonHolder> taxonMap = new HashMap();

    try {
        while (true) {
            if (mergeStream.readBoolean()) { // Singleton
                int cid = mergeStream.readInt();
                int intId = mergeStream.readInt();
                TaxonHolder<Taxon> holder;

                List<String> seqids = idMapping.getIds(intId);
                if (seqids.size() == 1) {
                    holder = new TaxonHolder(new Taxon(taxid++, seqids.get(0), ""));
                } else {
                    holder = new TaxonHolder(new Taxon(taxid++, "", ""));
                    for (String seqid : seqids) {
                        int id = taxid++;
                        distMap.put(id, 0.0);
                        TaxonHolder th = new TaxonHolder(new Taxon(id, seqid, ""));
                        th.setParent(holder);
                        holder.addChild(th);
                    }
                }

                lastMerged = holder;
                taxonMap.put(cid, holder);
            } else {
                int ci = mergeStream.readInt();
                int cj = mergeStream.readInt();
                int ck = mergeStream.readInt();
                double dist = (double) mergeStream.readInt() / DistanceCalculator.MULTIPLIER;

                TaxonHolder holder = new TaxonHolder(new Taxon(taxid++, "", ""));

                taxonMap.put(ck, holder);
                holder.addChild(taxonMap.get(ci));
                taxonMap.get(ci).setParent(holder);
                distMap.put(ci, dist);
                holder.addChild(taxonMap.get(cj));
                taxonMap.get(cj).setParent(holder);
                distMap.put(cj, dist);

                lastMerged = holder;
            }
        }
    } catch (EOFException e) {

    }

    if (lastMerged == null) {
        throw new IOException("No merges in file");
    }

    PrintStream newickTreeOut = new PrintStream(new File(args[2]));
    NewickPrintVisitor visitor = new NewickPrintVisitor(newickTreeOut, false, new NewickDistanceFactory() {

        public float getDistance(int i) {
            return distMap.get(i).floatValue();
        }

    });

    lastMerged.biDirectionDepthFirst(visitor);
    newickTreeOut.close();
}

From source file:TestCipher.java

public static void main(String args[]) throws Exception {
    Set set = new HashSet();
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        Point point = new Point(random.nextInt(1000), random.nextInt(2000));
        set.add(point);/*ww w.java2s.  c  o  m*/
    }
    int last = random.nextInt(5000);

    // Create Key
    byte key[] = password.getBytes();
    DESKeySpec desKeySpec = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

    // Create Cipher
    Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    desCipher.init(Cipher.ENCRYPT_MODE, secretKey);

    // Create stream
    FileOutputStream fos = new FileOutputStream("out.des");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    CipherOutputStream cos = new CipherOutputStream(bos, desCipher);
    ObjectOutputStream oos = new ObjectOutputStream(cos);

    // Write objects
    oos.writeObject(set);
    oos.writeInt(last);
    oos.flush();
    oos.close();

    // Change cipher mode
    desCipher.init(Cipher.DECRYPT_MODE, secretKey);

    // Create stream
    FileInputStream fis = new FileInputStream("out.des");
    BufferedInputStream bis = new BufferedInputStream(fis);
    CipherInputStream cis = new CipherInputStream(bis, desCipher);
    ObjectInputStream ois = new ObjectInputStream(cis);

    // Read objects
    Set set2 = (Set) ois.readObject();
    int last2 = ois.readInt();
    ois.close();

    // Compare original with what was read back
    int count = 0;
    if (set.equals(set2)) {
        System.out.println("Set1: " + set);
        System.out.println("Set2: " + set2);
        System.out.println("Sets are okay.");
        count++;
    }
    if (last == last2) {
        System.out.println("int1: " + last);
        System.out.println("int2: " + last2);
        System.out.println("ints are okay.");
        count++;
    }
    if (count != 2) {
        System.out.println("Problem during encryption/decryption");
    }
}

From source file:ZipCompress.java

public static void main(String[] args) throws IOException {
    FileOutputStream f = new FileOutputStream("test.zip");
    CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
    ZipOutputStream zos = new ZipOutputStream(csum);
    BufferedOutputStream out = new BufferedOutputStream(zos);
    zos.setComment("A test of Java Zipping");
    // No corresponding getComment(), though.
    for (int i = 0; i < args.length; i++) {
        System.out.println("Writing file " + args[i]);
        BufferedReader in = new BufferedReader(new FileReader(args[i]));
        zos.putNextEntry(new ZipEntry(args[i]));
        int c;// www. j ava2s . c om
        while ((c = in.read()) != -1)
            out.write(c);
        in.close();
    }
    out.close();
    // Checksum valid only after the file has been closed!
    System.out.println("Checksum: " + csum.getChecksum().getValue());
    // Now extract the files:
    System.out.println("Reading file");
    FileInputStream fi = new FileInputStream("test.zip");
    CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
    ZipInputStream in2 = new ZipInputStream(csumi);
    BufferedInputStream bis = new BufferedInputStream(in2);
    ZipEntry ze;
    while ((ze = in2.getNextEntry()) != null) {
        System.out.println("Reading file " + ze);
        int x;
        while ((x = bis.read()) != -1)
            System.out.write(x);
    }
    System.out.println("Checksum: " + csumi.getChecksum().getValue());
    bis.close();
    // Alternative way to open and read zip files:
    ZipFile zf = new ZipFile("test.zip");
    Enumeration e = zf.entries();
    while (e.hasMoreElements()) {
        ZipEntry ze2 = (ZipEntry) e.nextElement();
        System.out.println("File: " + ze2);
        // ... and extract the data as before
    }
}

From source file:com.manning.blogapps.chapter10.examples.AuthPostJava.java

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        System.out.println("USAGE: authpost <username> <password> <filepath> <url>");
        System.exit(-1);//from   w  ww. j a v  a  2s .com
    }
    String credentials = args[0] + ":" + args[1];
    String filepath = args[2];

    URL url = new URL(args[3]);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    conn.setRequestProperty("Authorization",
            "Basic " + new String(Base64.encodeBase64(credentials.getBytes())));

    File upload = new File(filepath);
    conn.setRequestProperty("name", upload.getName());

    String contentType = "application/atom+xml; charset=utf8";
    if (filepath.endsWith(".gif"))
        contentType = "image/gif";
    else if (filepath.endsWith(".jpg"))
        contentType = "image/jpg";
    conn.setRequestProperty("Content-type", contentType);

    BufferedInputStream filein = new BufferedInputStream(new FileInputStream(upload));
    BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
    byte buffer[] = new byte[8192];
    for (int count = 0; count != -1;) {
        count = filein.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    filein.close();
    out.close();

    String s = null;
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((s = in.readLine()) != null) {
        System.out.println(s);
    }
}

From source file:test1.ApacheHttpRestClient2.java

public final static void main(String[] args) {

    HttpClient httpClient = new DefaultHttpClient();
    try {//  w  w w. ja v  a2 s  .  c  o  m
        // this ona api call returns results in a JSON format
        HttpGet httpGetRequest = new HttpGet("https://api.ona.io/api/v1/users");

        // Execute HTTP request
        HttpResponse httpResponse = httpClient.execute(httpGetRequest);

        System.out.println("------------------HTTP RESPONSE----------------------");
        System.out.println(httpResponse.getStatusLine());
        System.out.println("------------------HTTP RESPONSE----------------------");

        // Get hold of the response entity
        HttpEntity entity = httpResponse.getEntity();

        // If the response does not enclose an entity, there is no need
        // to bother about connection release
        byte[] buffer = new byte[1024];
        if (entity != null) {
            InputStream inputStream = entity.getContent();
            try {
                int bytesRead = 0;
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                while ((bytesRead = bis.read(buffer)) != -1) {
                    String chunk = new String(buffer, 0, bytesRead);
                    FileWriter file = new FileWriter("C:\\Users\\fred\\Desktop\\webicons\\output.txt");
                    //file.write(chunk.toJSONString());
                    file.write(chunk.toCharArray());
                    file.flush();
                    file.close();

                    System.out.print(chunk);
                    System.out.println(chunk);
                }
            } catch (IOException ioException) {
                // In case of an IOException the connection will be released
                // back to the connection manager automatically
                ioException.printStackTrace();
            } catch (RuntimeException runtimeException) {
                // In case of an unexpected exception you may want to abort
                // the HTTP request in order to shut down the underlying
                // connection immediately.
                httpGetRequest.abort();
                runtimeException.printStackTrace();
            }
            //          try {
            //              FileWriter file = new FileWriter("C:\\Users\\fred\\Desktop\\webicons\\output.json");
            //                file.write(bis.toJSONString());
            //                file.flush();
            //                file.close();
            //
            //                System.out.print(bis);
            //          } catch (Exception e) {
            //          }

            finally {
                // Closing the input stream will trigger connection release
                try {
                    inputStream.close();
                } catch (Exception ignore) {
                }
            }
        }
    } catch (ClientProtocolException e) {
        // thrown by httpClient.execute(httpGetRequest)
        e.printStackTrace();
    } catch (IOException e) {
        // thrown by entity.getContent();
        e.printStackTrace();
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.guns.media.tools.yuv.MediaTool.java

/**
 * @param args the command line arguments
 *//* www  .  j  a  v  a2 s  . c o m*/
public static void main(String[] args) throws IOException {

    try {
        Options options = getOptions();
        CommandLine cmd = null;
        int offset = 0;
        CommandLineParser parser = new GnuParser();
        cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            printHelp(options);
            exit(1);
        }

        if (cmd.hasOption("offset")) {
            offset = new Integer(cmd.getOptionValue("offset"));
        }
        int frame = new Integer(cmd.getOptionValue("f"));

        //  int scale = new Integer(args[2]);
        BufferedInputStream if1 = new BufferedInputStream(new FileInputStream(cmd.getOptionValue("if1")));
        BufferedInputStream if2 = new BufferedInputStream(new FileInputStream(cmd.getOptionValue("if2")));

        DataStorage.create(new Integer(cmd.getOptionValue("f")));

        int width = new Integer(cmd.getOptionValue("w"));
        int height = new Integer(cmd.getOptionValue("h"));
        LookUp.initSSYUV(width, height);
        //  int[][] frame1 = new int[width][height];
        //  int[][] frame2 = new int[width][height];
        int nRead;
        int fRead;
        byte[] data = new byte[width * height + ((width * height) / 2)];
        byte[] data1 = new byte[width * height + ((width * height) / 2)];
        int frames = 0;
        long start_ms = System.currentTimeMillis() / 1000L;
        long end_ms = start_ms;

        if (offset > 0) {
            if1.skip(((width * height + ((width * height) / 2)) * offset));
        } else if (offset < 0) {
            if2.skip(((width * height + ((width * height) / 2)) * (-1 * offset)));
        }

        if (cmd.hasOption("psnr")) {
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                PSNRCalculatorThread wt = new PSNRCalculatorThread(data_out, data1_out, frames, width, height);
                executor.execute(wt);
                frames++;

            }
            executor.shutdown();
            end_ms = System.currentTimeMillis();

            System.out.println("Frame Rate :" + frames * 1000 / ((end_ms - start_ms)));
            for (int i = 0; i < frames; i++) {
                System.out.println(
                        i + "," + 10 * Math.log10((255 * 255) / (DataStorage.getFrame(i) / (width * height))));

            }
        }
        if (cmd.hasOption("sub")) {

            RandomAccessFile raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw");

            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1)) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                ImageSubstractThread wt = new ImageSubstractThread(data_out, data1_out, frames, width, height,
                        raf);
                //wt.run();
                executor.execute(wt);

                frames++;

            }
            executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));

            raf.close();
        }
        if (cmd.hasOption("ss") && !cmd.getOptionValue("o").matches("-")) {

            RandomAccessFile raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw");

            // RandomAccessFile ra =  new RandomAccessFile(cmd.getOptionValue("o"), "rw");
            // MappedByteBuffer raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, ((width*height)+(width*height/2))*frame);
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                SidebySideImageThread wt = new SidebySideImageThread(data_out, data1_out, frames, width, height,
                        raf);
                // MPSidebySideImageThread wt = new MPSidebySideImageThread(data_out, data1_out, frames, width, height, ra);
                frames++;
                // wt.run();

                executor.execute(wt);
            }
            executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;

            while (!executor.isTerminated()) {

            }

            raf.close();
        }
        if (cmd.hasOption("ss") && cmd.getOptionValue("o").matches("-")) {

            PrintStream stdout = new PrintStream(System.out);

            // RandomAccessFile ra =  new RandomAccessFile(cmd.getOptionValue("o"), "rw");
            // MappedByteBuffer raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, ((width*height)+(width*height/2))*frame);
            // ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                SidebySideImageThread wt = new SidebySideImageThread(data_out, data1_out, frames, width, height,
                        stdout);
                // MPSidebySideImageThread wt = new MPSidebySideImageThread(data_out, data1_out, frames, width, height, ra);
                frames++;
                // wt.run();

                wt.run();
            }

            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));

            stdout.close();
        }
        if (cmd.hasOption("image")) {

            System.setProperty("java.awt.headless", "true");
            //ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1)) {

                if (frames == frame) {
                    byte[] data_out = data.clone();
                    byte[] data1_out = data1.clone();

                    Frame f1 = new Frame(data_out, width, height, Frame.YUV420);
                    Frame f2 = new Frame(data1_out, width, height, Frame.YUV420);
                    //       System.out.println(cmd.getOptionValue("o"));
                    ExtractImageThread wt = new ExtractImageThread(f1, frames,
                            cmd.getOptionValue("if1") + "frame1-" + cmd.getOptionValue("o"));
                    ExtractImageThread wt1 = new ExtractImageThread(f2, frames,
                            cmd.getOptionValue("if2") + "frame2-" + cmd.getOptionValue("o"));
                    //   executor.execute(wt);
                    executor.execute(wt);
                    executor.execute(wt1);
                }
                frames++;

            }
            executor.shutdown();
            //  executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));
        }

    } catch (ParseException ex) {
        Logger.getLogger(MediaTool.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:kilim.tools.Weaver.java

/**
 * <pre>/*from  w  w w .  ja  va 2  s  . co  m*/
 * Usage: java kilim.tools.Weaver -d &lt;output directory&gt; {source classe, jar, directory ...}
 * </pre>
 * 
 * If directory names or jar files are given, all classes in that container are processed. It is
 * perfectly fine to specify the same directory for source and output like this: 
 * <pre>
 *    java kilim.tools.Weaver -d ./classes ./classes
 * </pre>
 * Ensure that all classes to be woven are in the classpath. The output directory does not have to be 
 * in the classpath during weaving.
 *   
 * @see #weave(List) for run-time weaving.
 */
public static void main(String[] args) throws IOException {
    // System.out.println(System.getProperty("java.class.path"));

    Detector detector = Detector.DEFAULT;

    String currentName = null;
    for (String name : parseArgs(args)) {
        try {
            if (name.endsWith(".class")) {
                if (exclude(name))
                    continue;
                currentName = name;
                weaveFile(name, new BufferedInputStream(new FileInputStream(name)), detector);
            } else if (name.endsWith(".jar")) {
                for (FileLister.Entry fe : new FileLister(name)) {
                    currentName = fe.getFileName();
                    if (currentName.endsWith(".class")) {
                        currentName = currentName.substring(0, currentName.length() - 6).replace('/', '.');
                        if (exclude(currentName))
                            continue;
                        weaveFile(currentName, fe.getInputStream(), detector);
                    }
                }
            } else if (new File(name).isDirectory()) {
                for (FileLister.Entry fe : new FileLister(name)) {
                    currentName = fe.getFileName();
                    if (currentName.endsWith(".class")) {
                        if (exclude(currentName))
                            continue;
                        weaveFile(currentName, fe.getInputStream(), detector);
                    }
                }
            } else {
                weaveClass(name, detector);
            }
        } catch (KilimException ke) {
            log.error("Error weaving " + currentName + ". " + ke.getMessage());
            // ke.printStackTrace();
            System.exit(1);
        } catch (IOException ioe) {
            log.error("Unable to find/process '" + currentName + "'");
            System.exit(1);
        } catch (Throwable t) {
            log.error("Error weaving " + currentName);
            t.printStackTrace();
            System.exit(1);
        }
    }
    System.exit(err);
}