Example usage for java.io FileInputStream skip

List of usage examples for java.io FileInputStream skip

Introduction

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

Prototype

public long skip(long n) throws IOException 

Source Link

Document

Skips over and discards n bytes of data from the input stream.

Usage

From source file:aarddict.Volume.java

public void verify(VerifyProgressListener listener) throws IOException, NoSuchAlgorithmException {
    FileInputStream fis = new FileInputStream(origFile);
    fis.skip(44);
    byte[] buff = new byte[1 << 16];
    MessageDigest m = MessageDigest.getInstance("SHA-1");
    int readCount;
    long totalReadCount = 0;
    double totalBytes = origFile.length() - 44;
    boolean proceed = true;
    while ((readCount = fis.read(buff)) != -1) {
        m.update(buff, 0, readCount);/*from  w w  w  . jav  a  2 s .  co  m*/
        totalReadCount += readCount;
        proceed = listener.updateProgress(this, totalReadCount / totalBytes);
    }
    fis.close();
    if (proceed) {
        String calculated = Volume.toHex(m.digest());
        Log.d(TAG, "calculated: " + calculated + " actual: " + sha1sum);
        listener.verified(this, calculated.equals(this.sha1sum));
    }
}

From source file:thv.th.reader.SavegameReader.java

public static THMap read(FileInputStream frameStream, FileInputStream frameListStream,
        FileInputStream frameElementStream, File frameTabFile, File frameChunksFile, THPalette framePalette,
        FileInputStream saveStream, ABuffer blockTabStream, FileInputStream blockChunkStream,
        THPalette blockPalette, Color background) throws IOException {
    Vector<BufferedImage> tiles = ChunksReader.readAll(blockChunkStream, blockTabStream, blockPalette,
            background);//from ww  w .  j  av a 2s . c  om
    THMap result = new THMap();

    saveStream.getChannel().position(13);

    for (int y = 0; y < 128; ++y) {
        for (int x = 0; x < 128; ++x) {
            int pos = (int) saveStream.getChannel().position() + 21;
            int anim = EndianUtils.readSwappedShort(saveStream);

            int layer0id = saveStream.read();
            int layer1id = saveStream.read();
            int layer2id = saveStream.read();

            layer0id = LevelReader.tileMap[layer0id];
            layer1id = LevelReader.tileMap[layer1id];
            layer2id = LevelReader.tileMap[layer2id];

            BufferedImage l0 = tiles.elementAt(layer0id);
            BufferedImage l1 = null;
            BufferedImage l2 = null;
            if (layer1id > 0) {
                l1 = tiles.elementAt(layer1id);
            }

            if (layer2id > 0) {
                l2 = tiles.elementAt(layer2id);
            }

            saveStream.skip(1);
            int extra = saveStream.read();
            saveStream.skip(1);

            Tile tile = new Tile(anim, l0, l1, l2, pos);

            switch (extra >>> 4) {
            case 2:
            case 10:
                tile.setShadow1(tiles.get(154));
                break;
            case 3:
            case 11:
                tile.setShadow0(tiles.get(74));
                tile.setShadow1(tiles.get(154));
                break;
            case 6:
            case 7:
            case 14:
            case 15:
                tile.setShadow0(tiles.get(73));
                tile.setShadow1(tiles.get(154));
                break;
            case 1:
            case 9:
                tile.setShadow0(tiles.get(74));
                break;
            case 4:
            case 5:
            case 12:
            case 13:
                tile.setShadow0(tiles.get(73));
                break;

            }

            switch (extra & 0xf) {
            case 1:
                tile.setLitter(FramesReader.readByIndex(3737, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 2:
                tile.setLitter(FramesReader.readByIndex(3738, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 3:
                tile.setLitter(FramesReader.readByIndex(3739, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 4:
                tile.setLitter(FramesReader.readByIndex(4533, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 5:
                tile.setLitter(FramesReader.readByIndex(3741, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 6:
                tile.setLitter(FramesReader.readByIndex(4542, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 7:
                tile.setLitter(FramesReader.readByIndex(3742, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            }

            long nextPos = saveStream.getChannel().position();

            readObjectInfo(saveStream, tile, frameStream, frameListStream, frameElementStream, frameTabFile,
                    frameChunksFile, framePalette);
            result.setTile(x, y, tile);

            saveStream.getChannel().position(nextPos);
        }
    }

    /*for(int y = 0; y < 128; ++y) {
    for(int x = 0; x < 128; ++x) {
        int pid = EndianUtils.readSwappedShort(mapStream);
                
        result.getTile(x, y).setParcel(pid);
    }
    }*/

    saveStream.close();
    return result;
}

From source file:edu.wustl.mir.erl.ihe.xdsi.util.StoreSCU.java

public void send(final File f, long fmiEndPos, String cuid, String iuid, String filets)
        throws IOException, InterruptedException, ParserConfigurationException, SAXException {
    String ts = selectTransferSyntax(cuid, filets);

    if (f.getName().endsWith(".xml")) {
        Attributes parsedDicomFile = SAXReader.parse(new FileInputStream(f));
        if (CLIUtils.updateAttributes(parsedDicomFile, attrs, uidSuffix))
            iuid = parsedDicomFile.getString(Tag.SOPInstanceUID);
        if (!ts.equals(filets)) {
            Decompressor.decompress(parsedDicomFile, filets);
        }//w  w  w. jav a 2 s. com
        as.cstore(cuid, iuid, priority, new DataWriterAdapter(parsedDicomFile), ts,
                rspHandlerFactory.createDimseRSPHandler(f));
    } else {
        if (uidSuffix == null && attrs.isEmpty() && ts.equals(filets)) {
            FileInputStream in = new FileInputStream(f);
            try {
                in.skip(fmiEndPos);
                InputStreamDataWriter data = new InputStreamDataWriter(in);
                as.cstore(cuid, iuid, priority, data, ts, rspHandlerFactory.createDimseRSPHandler(f));
            } finally {
                SafeClose.close(in);
            }
        } else {
            DicomInputStream in = new DicomInputStream(f);
            try {
                in.setIncludeBulkData(IncludeBulkData.URI);
                Attributes data = in.readDataset(-1, -1);
                if (CLIUtils.updateAttributes(data, attrs, uidSuffix))
                    iuid = data.getString(Tag.SOPInstanceUID);
                if (!ts.equals(filets)) {
                    Decompressor.decompress(data, filets);
                }
                as.cstore(cuid, iuid, priority, new DataWriterAdapter(data), ts,
                        rspHandlerFactory.createDimseRSPHandler(f));
            } finally {
                SafeClose.close(in);
            }
        }
    }
}

From source file:org.apache.hadoop.hdfs.BlockReaderLocal.java

private BlockReaderLocal(Configuration conf, String hdfsfile, Block block, Token<BlockTokenIdentifier> token,
        long startOffset, long length, BlockLocalPathInfo pathinfo, FileInputStream dataIn) throws IOException {
    super(new Path("/blk_" + block.getBlockId() + ":of:" + hdfsfile) /*too non path-like?*/, 1);
    this.startOffset = startOffset;
    this.dataIn = dataIn;
    long toSkip = startOffset;
    while (toSkip > 0) {
        long skipped = dataIn.skip(toSkip);
        if (skipped == 0) {
            throw new IOException("Couldn't initialize input stream");
        }/*from  w  w  w.  j  ava  2  s . c  o m*/
        toSkip -= skipped;
    }
}

From source file:filesrv.Data.java

public void sendFileBlocking(ClientHandler handler) throws IOException, BadRequestException {
    File file = getFile();/*from   ww  w.ja  v  a 2  s  . com*/

    fileLength = file.length();
    String header = makeFileResponseHeader(handler);

    FileInputStream in = null;
    byte buffer[] = new byte[1024 * 1024];
    try {
        in = new FileInputStream(file);
        if (startRange > 0) {
            logger.finest("Will skip: " + startRange);
            in.skip(startRange);
        }
        int i = 0;

        i = in.read(buffer);
        logger.finest("Sending HTTP header for file.");
        handler.sendClientBytes(header);

        handler.setDataMode(DataMode.BINARY, DataType.OUT);
        logger.finest("Sending file data: " + file);
        long remain = fileLength - startRange;
        logger.finest("Remain: " + remain + ", startRange: " + startRange + ", i: " + i);

        while (i != -1 && remain != 0) {
            if (i > remain)
                i = (int) remain;

            handler.sendClientBinary(buffer, 0, i);
            startRange += i;

            remain = fileLength - startRange;
            i = in.read(buffer);
            logger.finest("Remain: " + remain + ", startRange: " + startRange + ", i: " + i);
            Thread.currentThread().yield();
        }
        logger.fine("Sent the file!");
    } catch (Exception er) {
        logger.info("Error sending file: " + er);
    } finally {
        if (in != null)
            in.close();
        handler.setDataMode(DataMode.BYTE, DataType.OUT);
    }

    if (false) {
        handler.closeConnection();
    } else {
        //so that we can take more req.
        clean();
    }
}

From source file:org.opensilk.music.cast.CastWebServer.java

private Response serveFile(File file, String mime, Map<String, String> headers) {
    Response res;//from   w  w w. j a  v a2 s  .  co m
    try {
        // Calculate etag
        String etag = Integer
                .toHexString((file.getAbsolutePath() + file.lastModified() + "" + file.length()).hashCode());

        // Support (simple) skipping:
        long startFrom = 0;
        long endAt = -1;
        String range = headers.get("range");
        if (range != null) {
            if (range.startsWith("bytes=")) {
                range = range.substring("bytes=".length());
                int minus = range.indexOf('-');
                try {
                    if (minus > 0) {
                        startFrom = Long.parseLong(range.substring(0, minus));
                        endAt = Long.parseLong(range.substring(minus + 1));
                    }
                } catch (NumberFormatException ignored) {
                }
            }
        }

        // Change return code and add Content-Range header when skipping is requested
        long fileLen = file.length();
        if (range != null && startFrom >= 0) {
            if (startFrom >= fileLen) {
                res = createResponse(Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, "");
                res.addHeader("Content-Range", "bytes 0-0/" + fileLen);
                res.addHeader("ETag", etag);
            } else {
                if (endAt < 0) {
                    endAt = fileLen - 1;
                }
                long newLen = endAt - startFrom + 1;
                if (newLen < 0) {
                    newLen = 0;
                }

                final long dataLen = newLen;
                FileInputStream fis = new FileInputStream(file) {
                    @Override
                    public int available() throws IOException {
                        return (int) dataLen;
                    }
                };
                fis.skip(startFrom);

                res = createResponse(Response.Status.PARTIAL_CONTENT, mime, fis);
                res.addHeader("Content-Length", "" + dataLen);
                res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
                res.addHeader("ETag", etag);
            }
        } else {
            if (etag.equals(headers.get("if-none-match")))
                res = createResponse(Response.Status.NOT_MODIFIED, mime, "");
            else {
                res = createResponse(Response.Status.OK, mime, new FileInputStream(file));
                res.addHeader("Content-Length", "" + fileLen);
                res.addHeader("ETag", etag);
            }
        }
    } catch (IOException ioe) {
        res = createResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT,
                "FORBIDDEN: Reading file failed.");
    }

    return res;
}

From source file:org.apache.carbondata.core.datastore.filesystem.LocalCarbonFile.java

/**
 * return the datainputStream which is seek to the offset of file
 *
 * @param path//from w w  w  .j  av  a 2s .c o  m
 * @param fileType
 * @param bufferSize
 * @param offset
 * @return DataInputStream
 * @throws IOException
 */
@Override
public DataInputStream getDataInputStream(String path, FileFactory.FileType fileType, int bufferSize,
        long offset) throws IOException {
    path = path.replace("\\", "/");
    path = FileFactory.getUpdatedFilePath(path, fileType);
    FileInputStream fis = new FileInputStream(path);
    long actualSkipSize = 0;
    long skipSize = offset;
    try {
        while (actualSkipSize != offset) {
            actualSkipSize += fis.skip(skipSize);
            skipSize = skipSize - actualSkipSize;
        }
    } catch (IOException ioe) {
        CarbonUtil.closeStream(fis);
        throw ioe;
    }
    return new DataInputStream(new BufferedInputStream(fis));
}

From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java

public void loadTextDataFluxSingle(File file) {
    try {//  w  w  w  .  j ava  2  s . c om
        RandomAccessFile in = new RandomAccessFile(file, "r");

        // Skip header
        in.readLine();
        in.readLine();
        in.readLine();

        // Skip Subject Information
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String startTimeInput = in.readLine();
        String commentsInput = in.readLine();

        String data = in.readLine();
        while (!data.startsWith("2) System Configuration")) {
            commentsInput += data;
            data = in.readLine();
        }
        // System configuration

        // in.readLine();
        in.readLine();
        String timeCounstantInput = in.readLine();
        String cameraGainInput = in.readLine();
        String exposureTimeInput = in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String resolutionInput = in.readLine();

        // in.readLine();
        // System.out.println(in.readLine());
        // in.readLine();

        // Parse important Size

        high = (new Scanner(resolutionInput.split(":")[1])).nextInt();
        wide = (new Scanner(resolutionInput.split(",")[1])).nextInt();
        int tot = 1;
        while (!data.startsWith("3) Flux Image Data")) {
            System.out.println(data);
            data = in.readLine();
        }
        in.readLine();
        // Parse Image Data
        /*
         * Close Random access file and switch to scanner first store pos
         * then move to correct point.
         */
        long pos = in.getFilePointer();
        in.close();

        FileInputStream fIn = new FileInputStream(file);
        fIn.skip(pos);

        BufferedInputStream bIn = new BufferedInputStream(fIn);
        Scanner sIn = new Scanner(bIn);

        short[][] holder = new short[wide][high];

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        StatusBarPanel stat = new StatusBarPanel();
        stat.setMaximum(high);
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(stat, BorderLayout.CENTER);
        f.setSize(200, 60);
        f.setVisible(true);

        // Skip over the heading values

        sIn.reset();

        for (int y = 0; y < high; y++) {
            System.out.println(sIn.nextInt());
            try {
                for (int x = 0; x < wide; x++) {
                    holder[x][y] = sIn.nextShort();
                }
            } catch (Throwable e) {

            }

        }
        addData(new Date(), holder);

        FrameFactroy.getFrame(new DynamicRangeImage(holder));
        // Start Image Data

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:NanoHTTPD.java

/**
 * Serves file from homeDir and its' subdirectories (only). Uses only URI,
 * ignores all headers and HTTP parameters.
 *//*from   w  ww . java2 s .  c o m*/
public Response serveFile(String uri, Properties header, File homeDir, boolean allowDirectoryListing) {
    // Make sure we won't die of an exception later
    if (!homeDir.isDirectory())
        return new Response(HTTP_INTERNALERROR, MIME_PLAINTEXT,
                "INTERNAL ERRROR: serveFile(): given homeDir is not a directory.");

    // Remove URL arguments
    uri = uri.trim().replace(File.separatorChar, '/');
    if (uri.indexOf('?') >= 0)
        uri = uri.substring(0, uri.indexOf('?'));

    // Prohibit getting out of current directory
    if (uri.startsWith("..") || uri.endsWith("..") || uri.indexOf("../") >= 0)
        return new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Won't serve ../ for security reasons.");

    File f = new File(homeDir, uri);
    if (!f.exists())
        return new Response(HTTP_NOTFOUND, MIME_PLAINTEXT, "Error 404, file not found.");

    // List the directory, if necessary
    if (f.isDirectory()) {
        // Browsers get confused without '/' after the
        // directory, send a redirect.
        if (!uri.endsWith("/")) {
            uri += "/";
            Response r = new Response(HTTP_REDIRECT, MIME_HTML,
                    "<html><body>Redirected: <a href=\"" + uri + "\">" + uri + "</a></body></html>");
            r.addHeader("Location", uri);
            return r;
        }

        // First try index.html and index.htm
        if (new File(f, "index.html").exists())
            f = new File(homeDir, uri + "/index.html");
        else if (new File(f, "index.htm").exists())
            f = new File(homeDir, uri + "/index.htm");

        // No index file, list the directory
        else if (allowDirectoryListing) {
            String[] files = f.list();
            String msg = "<html><body><h1>Directory " + uri + "</h1><br/>";

            if (uri.length() > 1) {
                String u = uri.substring(0, uri.length() - 1);
                int slash = u.lastIndexOf('/');
                if (slash >= 0 && slash < u.length())
                    msg += "<b><a href=\"" + uri.substring(0, slash + 1) + "\">..</a></b><br/>";
            }

            for (int i = 0; i < files.length; ++i) {
                File curFile = new File(f, files[i]);
                boolean dir = curFile.isDirectory();
                if (dir) {
                    msg += "<b>";
                    files[i] += "/";
                }

                msg += "<a href=\"" + encodeUri(uri + files[i]) + "\">" + files[i] + "</a>";

                // Show file size
                if (curFile.isFile()) {
                    long len = curFile.length();
                    msg += " &nbsp;<font size=2>(";
                    if (len < 1024)
                        msg += curFile.length() + " bytes";
                    else if (len < 1024 * 1024)
                        msg += curFile.length() / 1024 + "." + (curFile.length() % 1024 / 10 % 100) + " KB";
                    else
                        msg += curFile.length() / (1024 * 1024) + "."
                                + curFile.length() % (1024 * 1024) / 10 % 100 + " MB";

                    msg += ")</font>";
                }
                msg += "<br/>";
                if (dir)
                    msg += "</b>";
            }
            return new Response(HTTP_OK, MIME_HTML, msg);
        } else {
            return new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: No directory listing.");
        }
    }

    try {
        // Get MIME type from file name extension, if possible
        String mime = null;
        int dot = f.getCanonicalPath().lastIndexOf('.');
        if (dot >= 0)
            mime = (String) theMimeTypes.get(f.getCanonicalPath().substring(dot + 1).toLowerCase());
        if (mime == null)
            mime = MIME_DEFAULT_BINARY;

        // Support (simple) skipping:
        long startFrom = 0;
        String range = header.getProperty("Range");
        if (range != null) {
            if (range.startsWith("bytes=")) {
                range = range.substring("bytes=".length());
                int minus = range.indexOf('-');
                if (minus > 0)
                    range = range.substring(0, minus);
                try {
                    startFrom = Long.parseLong(range);
                } catch (NumberFormatException nfe) {
                }
            }
        }

        FileInputStream fis = new FileInputStream(f);
        fis.skip(startFrom);
        Response r = new Response(HTTP_OK, mime, fis);
        r.addHeader("Content-length", "" + (f.length() - startFrom));
        r.addHeader("Content-range", "" + startFrom + "-" + (f.length() - 1) + "/" + f.length());
        return r;
    } catch (IOException ioe) {
        return new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed.");
    }
}

From source file:ru.org.linux.util.image.ImageInfo.java

private void getJpgInfo(FileInputStream fileStream) throws IOException, BadImageException {
    if (fileStream.read() == 0xFF && fileStream.read() == 0xD8) {
        while (true) {
            int marker;
            do {//from w  w  w  .ja v a 2  s .  c  om
                marker = fileStream.read();
            } while (marker != 0xFF);
            do {
                marker = fileStream.read();
            } while (marker == 0xFF);

            if (((marker >= 0xC0) && (marker <= 0xC3)) || ((marker >= 0xC5) && (marker <= 0xCB))
                    || ((marker >= 0xCD) && (marker <= 0xCF))) {
                fileStream.skip(3);
                height = shortBigEndian((byte) fileStream.read(), (byte) fileStream.read());
                width = shortBigEndian((byte) fileStream.read(), (byte) fileStream.read());
                break;
            } else {
                int skip = shortBigEndian((byte) fileStream.read(), (byte) fileStream.read()) - 2;

                if (skip < 0) {
                    throw new BadImageException("Bad JPG image: " + filename);
                }

                fileStream.skip(skip);
            }
        }
    } else {
        throw new BadImageException("Bad JPG image: " + filename);
    }
}