Example usage for java.io BufferedInputStream skip

List of usage examples for java.io BufferedInputStream skip

Introduction

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

Prototype

public synchronized long skip(long n) throws IOException 

Source Link

Document

See the general contract of the skip method of InputStream.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {

    InputStream is = new FileInputStream("C:/test.txt");

    // input stream is converted to buffered input stream
    BufferedInputStream bis = new BufferedInputStream(is);

    // read until a single byte is available
    while (bis.available() > 0) {
        // skip single byte from the stream
        bis.skip(1);

        // read next available byte and convert to char
        char c = (char) bis.read();
        System.out.print(c);/*  w w w. j a  v  a  2s. c  o  m*/
    }
}

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

/**
 * @param args the command line arguments
 *//*from www. j ava  2  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:eu.scape_project.arc2warc.utils.ArcUtils.java

/**
 * Read the ARC record content into a byte array. Note that the record
 * content can be only read once, it is "consumed" afterwards.
 *
 * @param arcRecord ARC record./*w ww  . j ava 2  s  .  c o m*/
 * @return Content byte array.
 * @throws IOException If content is too large to be stored in a byte array.
 */
public static byte[] arcRecordPayloadToByteArray(ARCRecord arcRecord) throws IOException {
    // Byte point where the content of the ARC record begins
    int contentBegin = (int) arcRecord.getMetaData().getContentBegin();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedInputStream buffis = new BufferedInputStream(arcRecord);
    BufferedOutputStream buffos = new BufferedOutputStream(baos);
    byte[] tempBuffer = new byte[BUFFER_SIZE];
    int bytesRead;
    // skip header content
    buffis.skip(contentBegin);
    while ((bytesRead = buffis.read(tempBuffer)) != -1) {
        buffos.write(tempBuffer, 0, bytesRead);
    }
    buffis.close();
    buffos.flush();
    buffos.close();
    return baos.toByteArray();
}

From source file:eu.scape_project.spacip.ContainerProcessing.java

/**
 * Write ARC record content to output stream
 *
 * @param nativeArchiveRecord/*from   w ww  .  j  a  va 2  s.  c  o  m*/
 * @param outputStream Output stream
 * @throws IOException
 */
public static void recordToOutputStream(ArchiveRecord nativeArchiveRecord, OutputStream outputStream)
        throws IOException {
    ARCRecord arcRecord = (ARCRecord) nativeArchiveRecord;
    ARCRecordMetaData metaData = arcRecord.getMetaData();
    long contentBegin = metaData.getContentBegin();
    BufferedInputStream bis = new BufferedInputStream(arcRecord);
    BufferedOutputStream bos = new BufferedOutputStream(outputStream);
    byte[] tempBuffer = new byte[BUFFER_SIZE];
    int bytesRead;
    // skip record header
    bis.skip(contentBegin);
    while ((bytesRead = bis.read(tempBuffer)) != -1) {
        bos.write(tempBuffer, 0, bytesRead);
    }
    bos.flush();
    bis.close();
    bos.close();
}

From source file:com.sangupta.jerry.util.FileUtils.java

/**
 * Dump a given file into HEX starting at given offset and reading given number of rows where
 * a row consists of 16-bytes./*from  w  ww.ja v a 2  s .com*/
 * 
 * @param out
 * @param file
 * @param offset
 * @param maxRows
 * @throws IOException
 */
public static void hexDump(PrintStream out, File file, long offset, int maxRows) throws IOException {
    InputStream is = null;
    BufferedInputStream bis = null;

    try {
        is = new FileInputStream(file);
        bis = new BufferedInputStream(is);
        bis.skip(offset);

        int row = 0;
        if (maxRows == 0) {
            maxRows = Integer.MAX_VALUE;
        }

        StringBuilder builder1 = new StringBuilder(100);
        StringBuilder builder2 = new StringBuilder(100);

        while (bis.available() > 0) {
            out.printf("%04X  ", row * 16);
            for (int j = 0; j < 16; j++) {
                if (bis.available() > 0) {
                    int value = (int) bis.read();
                    builder1.append(String.format("%02X ", value));

                    if (!Character.isISOControl(value)) {
                        builder2.append((char) value);
                    } else {
                        builder2.append(".");
                    }
                } else {
                    for (; j < 16; j++) {
                        builder1.append("   ");
                    }
                }
            }
            out.print(builder1);
            out.println(builder2);
            row++;

            if (row > maxRows) {
                break;
            }

            builder1.setLength(0);
            builder2.setLength(0);
        }
    } finally {
        IOUtils.closeQuietly(bis);
        IOUtils.closeQuietly(is);
    }
}

From source file:com.openedit.generators.FileGenerator.java

protected InputStream streamBinary(WebPageRequest inReq, Page inPage, InputStream in, long start, long end,
        long length, Output inOut) throws IOException {
    OutputStream outs = inOut.getStream();
    if (start > -1) {
        BufferedInputStream buffer = new BufferedInputStream(in);
        long did = buffer.skip(start);
        if (did != start) {
            throw new OpenEditException("Could not seek to start");
        }/*  w ww  . j  a  v  a  2  s.  c o  m*/
        in = buffer;
    }
    if (end != -1) {
        getOutputFiller().fill(in, outs, length);
    } else {
        getOutputFiller().fill(in, outs);
    }
    return in;
}

From source file:co.cask.hydrator.plugin.batch.CopybookRecordReader.java

@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
    // Get configuration
    Configuration conf = context.getConfiguration();
    int fileStructure = net.sf.JRecord.Common.Constants.IO_FIXED_LENGTH;
    Path path = new Path(conf.get(CopybookInputFormat.COPYBOOK_INPUTFORMAT_DATA_HDFS_PATH));
    FileSystem fs = FileSystem.get(path.toUri(), conf);
    // Create input stream for the COBOL copybook contents
    InputStream inputStream = IOUtils
            .toInputStream(conf.get(CopybookInputFormat.COPYBOOK_INPUTFORMAT_CBL_CONTENTS), "UTF-8");
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    try {/*from  w w w .  j  a v a2  s  .c o m*/
        externalRecord = CopybookIOUtils.getExternalRecord(bufferedInputStream);
        recordByteLength = CopybookIOUtils.getRecordLength(externalRecord, fileStructure);

        LineProvider lineProvider = LineIOProvider.getInstance().getLineProvider(fileStructure,
                CopybookIOUtils.FONT);
        reader = LineIOProvider.getInstance().getLineReader(fileStructure, lineProvider);
        LayoutDetail copybook = CopybookIOUtils.getLayoutDetail(externalRecord);

        org.apache.hadoop.mapreduce.lib.input.FileSplit fileSplit = (org.apache.hadoop.mapreduce.lib.input.FileSplit) split;

        start = fileSplit.getStart();
        end = start + fileSplit.getLength();

        BufferedInputStream fileIn = new BufferedInputStream(fs.open(fileSplit.getPath()));
        // Jump to the point in the split at which the first complete record of the split starts,
        // if not the first InputSplit
        if (start != 0) {
            position = start - (start % recordByteLength) + recordByteLength;
            fileIn.skip(position);
        }
        reader.open(fileIn, copybook);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Hash.Hash.java

private static long startOfScanJPG(BufferedInputStream in) throws IOException {
    int c;//from  w ww .j  a  va 2  s .c  om
    long j = startOfImageJPG(in);
    if (j == -1)
        return -1;
    Boolean marker = false;
    while ((c = in.read()) != -1) {
        if (marker)
            //Not a marker(byte stuffing), shouldn't happen in header
            if (c == 0/* || c==216*/)
                marker = false;
            //Start of Quantization table, practically the image
            //Didn't work                else if (c == 219) return j;
            //Start of Scan
            else if (c == 0xDA /*218*/)
                return j;
            else {
                //                    System.out.print("ff" + Integer.toHexString(c) + " ");
                long jump = 256 * in.read() + in.read() - 2;
                //                    System.out.println(Long.toHexString(jump));
                do {
                    long skip = in.skip(jump);
                    if (skip < 0)
                        return -1;
                    jump -= skip;
                } while (jump > 0);
                j += jump + 2;
                marker = false;
            }
        else {
            if (c == 0xFF/*255*/) {
                marker = true;
                //                } else if (c == 0) {//byte stuffing
            } else {
                return -1;
            }
        }
        j++;
    }
    return -1;
}

From source file:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java

public int readObject(String path, byte[] bytes, long offset) throws IOException {
    File objectFile = new File(path);
    if (!objectFile.exists()) {
        throw new IOException("Unable to read: " + path);
    }//from w ww .  java2  s .c  om
    BufferedInputStream inputStream = null;
    int bytesRead = 0;
    try {
        inputStream = new BufferedInputStream(new FileInputStream(objectFile));
        if (offset > 0) {
            inputStream.skip(offset);
        }
        bytesRead = inputStream.read(bytes);
    } finally {
        if (inputStream != null)
            inputStream.close();
    }
    return bytesRead;
}

From source file:io.minio.MinioClient.java

/**
 * Skips data of up to given length in given input stream.
 *
 * @param inputStream  Input stream which is intance of {@link RandomAccessFile} or {@link BufferedInputStream}.
 * @param n            Length of bytes to skip.
 *///  ww  w  . j  av a2  s .c  om
private void skipStream(Object inputStream, long n) throws IOException, InsufficientDataException {
    RandomAccessFile file = null;
    BufferedInputStream stream = null;
    if (inputStream instanceof RandomAccessFile) {
        file = (RandomAccessFile) inputStream;
    } else if (inputStream instanceof BufferedInputStream) {
        stream = (BufferedInputStream) inputStream;
    } else {
        throw new IllegalArgumentException("unsupported input stream object");
    }

    if (file != null) {
        file.seek(file.getFilePointer() + n);
        return;
    }

    long bytesSkipped;
    long totalBytesSkipped = 0;

    while ((bytesSkipped = stream.skip(n - totalBytesSkipped)) >= 0) {
        totalBytesSkipped += bytesSkipped;
        if (totalBytesSkipped == n) {
            return;
        }
    }

    throw new InsufficientDataException(
            "Insufficient data.  bytes skipped " + totalBytesSkipped + " expected " + n);
}