Example usage for java.io RandomAccessFile length

List of usage examples for java.io RandomAccessFile length

Introduction

In this page you can find the example usage for java.io RandomAccessFile length.

Prototype

public native long length() throws IOException;

Source Link

Document

Returns the length of this file.

Usage

From source file:com.microsoft.azure.management.datalake.store.uploader.UploadMetadataGenerator.java

/**
 * Reads data from the given file into the given buffer, centered around the given file offset. The first half of the buffer will be
 * filled with data right before the given offset, while the remainder of the buffer will contain data right after it (of course, containing the byte at the given offset).
 * @param stream The stream to read from
 * @param buffer The buffer to read data into
 * @param fileReferenceOffset The offset to start reading from in the stream.
 * @return The number of bytes reads, which could be less than the length of the input buffer if we can't read due to the beginning or the end of the file.
 * @throws IOException Thrown if the stream being used is invalid or inaccessible.
 *//* w ww.  j a  va  2s  . c o  m*/
private static int readIntoBufferAroundReference(RandomAccessFile stream, byte[] buffer,
        long fileReferenceOffset) throws IOException {
    int length = buffer.length;
    //calculate start offset
    long fileStartOffset = fileReferenceOffset - length / 2;

    if (fileStartOffset < 0) {
        //offset is less than zero, adjust it, as well as the length we want to read
        length += (int) fileStartOffset;
        fileStartOffset = 0;
        if (length <= 0) {
            return 0;
        }
    }

    if (fileStartOffset + length > stream.length()) {
        //startOffset + length is beyond the end of the stream, adjust the length accordingly
        length = (int) (stream.length() - fileStartOffset);
        if (length <= 0) {
            return 0;
        }
    }

    //read the appropriate block of the file into the buffer, using symmetry with respect to its midpoint
    // we always initiate a seek from the origin of the file.
    stream.seek(0);
    stream.seek(fileStartOffset);
    int bufferOffset = 0;
    while (bufferOffset < length) {
        int bytesRead = stream.read(buffer, bufferOffset, length - bufferOffset);
        bufferOffset += bytesRead;
    }
    return length;
}

From source file:org.apache.storm.utils.ServerUtils.java

/**
 * Given a zip File input it will return its size
 * Only works for zip files whose uncompressed size is less than 4 GB,
 * otherwise returns the size module 2^32, per gzip specifications
 * @param myFile The zip file as input//  www. jav a 2s. co m
 * @throws IOException
 * @return zip file size as a long
 */
public static long zipFileSize(File myFile) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(myFile, "r");
    raf.seek(raf.length() - 4);
    long b4 = raf.read();
    long b3 = raf.read();
    long b2 = raf.read();
    long b1 = raf.read();
    long val = (b1 << 24) | (b2 << 16) + (b3 << 8) + b4;
    raf.close();
    return val;
}

From source file:com.liferay.lms.servlet.SCORMFileServerServlet.java

/**
 * Copy the given byte range of the given input to the given output.
 * @param input The input to copy the given range to the given output for.
 * @param output The output to copy the given range from the given input for.
 * @param start Start of the byte range.
 * @param length Length of the byte range.
 * @throws IOException If something fails at I/O level.
 *//*from   ww  w  .  j av a  2s.  c om*/
private static void copy(RandomAccessFile input, OutputStream output, long start, long length)
        throws IOException {
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    int read;

    if (input.length() == length) {
        // Write full range.
        while ((read = input.read(buffer)) > 0) {
            output.write(buffer, 0, read);
        }
    } else {
        // Write partial range.
        input.seek(start);
        long toRead = length;

        while ((read = input.read(buffer)) > 0) {
            if ((toRead -= read) > 0) {
                output.write(buffer, 0, read);
            } else {
                output.write(buffer, 0, (int) toRead + read);
                break;
            }
        }
    }
}

From source file:net.iharding.utils.FileUtils.java

/**   
 * RandomAccessFile   //w w  w.  j a v  a2  s.  co m
 *    
 * @param fileName ??   
 * @param content    
 */
public static void appendFile(String filePath, String content) {
    RandomAccessFile randomFile = null;
    try {
        // ???     
        randomFile = new RandomAccessFile(filePath, "rw");
        //      
        long fileLength = randomFile.length();
        //      
        randomFile.seek(fileLength);
        randomFile.writeUTF(content);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (randomFile != null) {
            try {
                randomFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:play.modules.netty.PlayHandler.java

public static void copyResponse(ChannelHandlerContext ctx, Request request, Response response,
        HttpRequest nettyRequest) throws Exception {
    Logger.trace("copyResponse: begin");
    //response.out.flush();

    // Decide whether to close the connection or not.

    HttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.status));
    nettyResponse.setHeader(SERVER, signature);

    if (response.contentType != null) {
        nettyResponse.setHeader(CONTENT_TYPE,
                response.contentType/* w w w . jav a  2s .  c om*/
                        + (response.contentType.startsWith("text/") && !response.contentType.contains("charset")
                                ? "; charset=utf-8"
                                : ""));
    } else {
        nettyResponse.setHeader(CONTENT_TYPE, "text/plain; charset=utf-8");
    }

    addToResponse(response, nettyResponse);

    final Object obj = response.direct;
    File file = null;
    InputStream is = null;
    if (obj instanceof File) {
        file = (File) obj;
    } else if (obj instanceof InputStream) {
        is = (InputStream) obj;
    }

    final boolean keepAlive = isKeepAlive(nettyRequest);
    if (file != null && file.isFile()) {
        try {
            nettyResponse = addEtag(nettyRequest, nettyResponse, file);
            if (nettyResponse.getStatus().equals(HttpResponseStatus.NOT_MODIFIED)) {

                Channel ch = ctx.getChannel();

                // Write the initial line and the header.
                ChannelFuture writeFuture = ch.write(nettyResponse);

                if (!keepAlive) {
                    // Close the connection when the whole content is written out.
                    writeFuture.addListener(ChannelFutureListener.CLOSE);
                }
            } else {
                nettyResponse.setHeader(CONTENT_TYPE, MimeTypes.getContentType(file.getName(), "text/plain"));
                RandomAccessFile raf = new RandomAccessFile(file, "r");
                long fileLength = raf.length();

                if (keepAlive) {
                    // Add 'Content-Length' header only for a keep-alive connection.
                    Logger.trace("file length is [" + fileLength + "]");
                    setContentLength(nettyResponse, fileLength);
                }

                Channel ch = ctx.getChannel();

                // Write the initial line and the header.
                ChannelFuture writeFuture = ch.write(nettyResponse);

                // Write the content.
                // If it is not a HEAD
                if (!nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
                    writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
                }
                if (!keepAlive) {
                    // Close the connection when the whole content is written out.
                    writeFuture.addListener(ChannelFutureListener.CLOSE);
                }
            }
        } catch (Exception e) {
            throw e;
        }
    } else if (is != null) {
        ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
        if (!nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
            writeFuture = ctx.getChannel().write(new ChunkedStream(is));
        }
        if (!keepAlive) {
            writeFuture.addListener(ChannelFutureListener.CLOSE);
        }
    } else {
        writeResponse(ctx, response, nettyResponse, nettyRequest);
    }
    Logger.trace("copyResponse: end");
}

From source file:org.red5.io.flv.FLVReader.java

public static long getDuration(File flvFile) {
    RandomAccessFile flv = null;
    try {// w  w w.  j a  va 2  s .com
        flv = new RandomAccessFile(flvFile, "r");
        long flvLength = flv.length();
        if (flvLength < 13) {
            return 0;
        }
        flv.seek(flvLength - 4);
        byte[] buf = new byte[4];
        flv.read(buf);
        long lastTagSize = 0;
        for (int i = 0; i < 4; i++) {
            lastTagSize += (buf[i] & 0x0ff) << ((3 - i) * 8);
        }
        if (lastTagSize == 0) {
            return 0;
        }
        flv.seek(flvLength - lastTagSize);
        flv.read(buf);
        long duration = 0;
        for (int i = 0; i < 3; i++) {
            duration += (buf[i] & 0x0ff) << ((2 - i) * 8);
        }
        duration += (buf[3] & 0x0ff) << 24; // extension byte
        return duration;
    } catch (IOException e) {
        return 0;
    } finally {
        try {
            if (flv != null) {
                flv.close();
            }
        } catch (IOException e) {
        }
        flv = null;
    }
}

From source file:play.modules.netty.PlayHandler.java

public static void serveStatic(RenderStatic renderStatic, ChannelHandlerContext ctx, Request request,
        Response response, HttpRequest nettyRequest, MessageEvent e) {
    Logger.trace("serveStatic: begin");
    HttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.status));
    nettyResponse.setHeader("Server", signature);
    try {//from w ww.  jav a  2  s  .  c  o  m
        VirtualFile file = Play.getVirtualFile(renderStatic.file);
        if (file != null && file.exists() && file.isDirectory()) {
            file = file.child("index.html");
            if (file != null) {
                renderStatic.file = file.relativePath();
            }
        }
        if ((file == null || !file.exists())) {
            serve404(new NotFound("The file " + renderStatic.file + " does not exist"), ctx, request,
                    nettyRequest);
        } else {
            boolean raw = false;
            for (PlayPlugin plugin : Play.plugins) {
                if (plugin.serveStatic(file, Request.current(), Response.current())) {
                    raw = true;
                    break;
                }
            }
            if (raw) {
                copyResponse(ctx, request, response, nettyRequest);
            } else {
                final File localFile = file.getRealFile();
                final boolean keepAlive = isKeepAlive(nettyRequest);
                nettyResponse = addEtag(nettyRequest, nettyResponse, localFile);

                if (nettyResponse.getStatus().equals(HttpResponseStatus.NOT_MODIFIED)) {

                    Channel ch = e.getChannel();

                    // Write the initial line and the header.
                    ChannelFuture writeFuture = ch.write(nettyResponse);
                    if (!keepAlive) {
                        // Write the content.
                        writeFuture.addListener(ChannelFutureListener.CLOSE);
                    }
                } else {

                    RandomAccessFile raf;
                    raf = new RandomAccessFile(localFile, "r");
                    long fileLength = raf.length();

                    Logger.trace("keep alive " + keepAlive);
                    Logger.trace(
                            "content type " + (MimeTypes.getContentType(localFile.getName(), "text/plain")));

                    if (keepAlive && !nettyResponse.getStatus().equals(HttpResponseStatus.NOT_MODIFIED)) {
                        // Add 'Content-Length' header only for a keep-alive connection.
                        Logger.trace("file length " + fileLength);
                        setContentLength(nettyResponse, fileLength);
                    }

                    nettyResponse.setHeader(CONTENT_TYPE,
                            (MimeTypes.getContentType(localFile.getName(), "text/plain")));

                    Channel ch = e.getChannel();

                    // Write the initial line and the header.
                    ch.write(nettyResponse);

                    // Write the content.
                    ChannelFuture writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));

                    if (!keepAlive) {
                        // Close the connection when the whole content is written out.
                        writeFuture.addListener(ChannelFutureListener.CLOSE);
                    }
                }
            }

        }
    } catch (Exception ez) {
        Logger.error(ez, "serveStatic for request %s", request.method + " " + request.url);
        try {
            ChannelBuffer buf = ChannelBuffers.copiedBuffer("Internal Error (check logs)".getBytes("utf-8"));
            nettyResponse.setContent(buf);
            ChannelFuture future = ctx.getChannel().write(nettyResponse);
            future.addListener(ChannelFutureListener.CLOSE);
        } catch (Exception ex) {
            Logger.error(ez, "serveStatic for request %s", request.method + " " + request.url);
        }
    }
    Logger.trace("serveStatic: end");
}

From source file:org.apache.jackrabbit.oak.plugins.segment.file.TarReader.java

/**
 * Tries to read an existing index from the given tar file. The index is
 * returned if it is found and looks valid (correct checksum, passes
 * sanity checks)./*ww w  . j  a  v  a 2  s . c  om*/
 *
 * @param file tar file
 * @param name name of the tar file, for logging purposes
 * @return tar index, or {@code null} if not found or not valid
 * @throws IOException if the tar file could not be read
 */
private static ByteBuffer loadAndValidateIndex(RandomAccessFile file, String name) throws IOException {
    long length = file.length();
    if (length % BLOCK_SIZE != 0 || length < 6 * BLOCK_SIZE || length > Integer.MAX_VALUE) {
        log.warn("Unexpected size {} of tar file {}", length, name);
        return null; // unexpected file size
    }

    // read the index metadata just before the two final zero blocks
    ByteBuffer meta = ByteBuffer.allocate(16);
    file.seek(length - 2 * BLOCK_SIZE - 16);
    file.readFully(meta.array());
    int crc32 = meta.getInt();
    int count = meta.getInt();
    int bytes = meta.getInt();
    int magic = meta.getInt();

    if (magic != INDEX_MAGIC) {
        return null; // magic byte mismatch
    }

    if (count < 1 || bytes < count * 24 + 16 || bytes % BLOCK_SIZE != 0) {
        log.warn("Invalid index metadata in tar file {}", name);
        return null; // impossible entry and/or byte counts
    }

    // this involves seeking backwards in the file, which might not
    // perform well, but that's OK since we only do this once per file
    ByteBuffer index = ByteBuffer.allocate(count * 24);
    file.seek(length - 2 * BLOCK_SIZE - 16 - count * 24);
    file.readFully(index.array());
    index.mark();

    CRC32 checksum = new CRC32();
    long limit = length - 2 * BLOCK_SIZE - bytes - BLOCK_SIZE;
    long lastmsb = Long.MIN_VALUE;
    long lastlsb = Long.MIN_VALUE;
    byte[] entry = new byte[24];
    for (int i = 0; i < count; i++) {
        index.get(entry);
        checksum.update(entry);

        ByteBuffer buffer = ByteBuffer.wrap(entry);
        long msb = buffer.getLong();
        long lsb = buffer.getLong();
        int offset = buffer.getInt();
        int size = buffer.getInt();

        if (lastmsb > msb || (lastmsb == msb && lastlsb > lsb)) {
            log.warn("Incorrect index ordering in tar file {}", name);
            return null;
        } else if (lastmsb == msb && lastlsb == lsb && i > 0) {
            log.warn("Duplicate index entry in tar file {}", name);
            return null;
        } else if (offset < 0 || offset % BLOCK_SIZE != 0) {
            log.warn("Invalid index entry offset in tar file {}", name);
            return null;
        } else if (size < 1 || offset + size > limit) {
            log.warn("Invalid index entry size in tar file {}", name);
            return null;
        }

        lastmsb = msb;
        lastlsb = lsb;
    }

    if (crc32 != (int) checksum.getValue()) {
        log.warn("Invalid index checksum in tar file {}", name);
        return null; // checksum mismatch
    }

    index.reset();
    return index;
}

From source file:com.ieasy.basic.util.file.FileUtils.java

/**
 * ??/* w  ww . jav  a  2 s . c om*/
 * 
 * @param fileName
 *            ??
 */
public static void readFileByRandomAccess(String fileName) {
    RandomAccessFile randomFile = null;
    try {
        System.out.println("??");
        // ????
        randomFile = new RandomAccessFile(fileName, "r");
        // 
        long fileLength = randomFile.length();
        // ?
        int beginIndex = (fileLength > 4) ? 4 : 0;
        // ?beginIndex?
        randomFile.seek(beginIndex);
        byte[] bytes = new byte[10];
        int byteread = 0;
        // 10?10
        // ?byteread
        while ((byteread = randomFile.read(bytes)) != -1) {
            System.out.write(bytes, 0, byteread);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (randomFile != null) {
            try {
                randomFile.close();
            } catch (IOException e1) {
            }
        }
    }
}

From source file:dk.netarkivet.common.utils.cdx.BinSearch.java

/** Perform a binary search for a string in a file.
 * Returns the position of a line that begins with 'find'.
 * Note that this may not be the first line, if there be duplicates.
 * @param in the RandomAccessFile/*w  w  w.j  a va 2  s  . c om*/
 * @param find The String to look for in the above file
 * @throws IOException If some I/O error occurs
 * @return The index of a line matching find, or -1 if none found.
 */
private static long binSearch(RandomAccessFile in, String find) throws IOException {
    // The starting position for the binary search.  Always
    // at the start of a line that's < the wanted line.
    long startpos = 0;
    // Ensure that startpos isn't a match.
    in.seek(startpos);
    String line = in.readLine();
    if (line == null) {
        return -1;
    }
    if (compare(line, find) == 0) {
        return startpos;
    }
    // The ending position for the binary search.  Always
    // *after* a line that >= the wanted line (which also means
    // at the start of a line that's > the wanted line, or at EOF
    long endpos = in.length();

    // Set file pos to first line after middle.
    findMiddleLine(in, startpos, endpos);

    // When done searching, midpos points to a matching line, if any
    // Until the search is done, both endpos and startpos point
    // at non-matching lines (or EOF), and startpos < prevpos < endpos
    long prevpos = in.getFilePointer();
    do {
        line = in.readLine();
        if (line == null) {
            log.debug("Internal: Ran past end of file in '" + in + "' at " + endpos);
            return -1;
        }
        int cmp = compare(line, find);
        if (cmp > 0) {
            endpos = prevpos;
        } else if (cmp < 0) {
            startpos = prevpos;
        } else {
            return prevpos;
        }
        if (startpos == endpos) {
            return -1;
        }
        prevpos = findMiddleLine(in, startpos, endpos);
        if (prevpos == -1) {
            return -1;
        }
    } while (true);
}