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.android.volley.toolbox.DownloadNetwork.java

/** Reads the contents of HttpEntity into a byte[]. 
 * @param request //from   w  w  w  .  j  ava2s.c o  m
 * @param acessfile */
private byte[] entityToBytes(HttpEntity entity, DownOrUpRequest request, RandomAccessFile acessfile)
        throws IOException, ServerError {
    //        PoolingByteArrayOutputStream bytes =
    //                new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    long length = acessfile.length();
    request.setmMaxLength(entity.getContentLength() + length);
    byte[] buffer = new byte[1024];
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        int count;
        while ((count = in.read(buffer)) != -1) {
            if (request.isCanceled()) {
                break;
            }
            acessfile.write(buffer, 0, count);
            length += count;
            request.doProcess(length);

        }
        return null;
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        //            bytes.close();

    }
}

From source file:interactivespaces.master.resource.deployment.internal.NettyHttpRemoteRepositoryMasterWebServerHandler.java

/**
 * Attempt to handle an HTTP request by scanning through all registered
 * handlers./*from  w w  w . java  2  s  .  c o  m*/
 *
 * @param context
 *          the context for the request
 * @param req
 *          the request
 * @return {@code true} if the request was handled
 *
 * @throws IOException
 *           something bad happened
 */
private boolean handleWebRequest(ChannelHandlerContext context, HttpRequest req) throws IOException {
    String url = req.getUri();
    int pos = url.indexOf('?');
    if (pos != -1)
        url = url.substring(0, pos);

    int luriPrefixLength = uriPrefix.length();
    String bundleName = url.substring(url.indexOf(uriPrefix) + luriPrefixLength);

    File file = featureRepository.getFeatureFile(bundleName);
    if (file == null) {
        return false;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        // sendError(ctx, NOT_FOUND);

        return false;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);

    Channel channel = context.getChannel();

    // Write the initial line and the header.
    channel.write(response);

    // Write the content.
    ChannelFuture writeFuture;
    if (channel.getPipeline().get(SslHandler.class) != null) {
        // Cannot use zero-copy with HTTPS.
        writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = channel.write(region);
        writeFuture.addListener(new ChannelFutureProgressListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                region.releaseExternalResources();
            }

            @Override
            public void operationProgressed(ChannelFuture arg0, long arg1, long arg2, long arg3)
                    throws Exception {
                // Do nothing
            }

        });
    }

    // Decide whether to close the connection or not.
    if (!isKeepAlive(req)) {
        // Close the connection when the whole content is written out.
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }

    return true;
}

From source file:dk.netarkivet.common.utils.FileUtils.java

/**
 * Read the last line in a file. Note this method is not UTF-8 safe.
 *
 * @param file input file to read last line from.
 * @return The last line in the file (ending newline is irrelevant),
 * returns an empty string if file is empty.
 * @throws ArgumentNotValid on null argument, or file is not a readable
 * file.//from  w ww .ja v a2  s .  co m
 * @throws IOFailure on IO trouble reading file.
 */
public static String readLastLine(File file) {
    ArgumentNotValid.checkNotNull(file, "File file");
    if (!file.isFile() || !file.canRead()) {
        final String errMsg = "File '" + file.getAbsolutePath() + "' is not a readable file.";
        log.warn(errMsg);
        throw new ArgumentNotValid(errMsg);
    }
    if (file.length() == 0) {
        return "";
    }
    RandomAccessFile rafile = null;
    try {
        rafile = new RandomAccessFile(file, "r");
        //seek to byte one before end of file (remember we know the file is
        // not empty) - this ensures that an ending newline is not read
        rafile.seek(rafile.length() - 2);
        //now search to the last linebreak, or beginning of file
        while (rafile.getFilePointer() != 0 && rafile.read() != '\n') {
            //search back two, because we just searched forward one to find
            //newline
            rafile.seek(rafile.getFilePointer() - 2);
        }
        return rafile.readLine();
    } catch (IOException e) {
        final String errMsg = "Unable to access file '" + file.getAbsolutePath() + "'";
        log.warn(errMsg, e);
        throw new IOFailure(errMsg, e);
    } finally {
        try {
            if (rafile != null) {
                rafile.close();
            }
        } catch (IOException e) {
            log.debug("Unable to close file '" + file.getAbsolutePath() + "' after reading", e);
        }
    }
}

From source file:com.eincs.decanter.handler.StaticFileHandler.java

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    if (!(e.getMessage() instanceof DecanterRequest)) {
        super.messageReceived(ctx, e);
        return;/*  w  w  w.  j a va  2  s.  c o m*/
    }

    final DecanterRequest request = (DecanterRequest) e.getMessage();
    final String path = request.getPath();
    if (!path.startsWith(this.path)) {
        super.messageReceived(ctx, e);
        return;
    }

    if (request.getMethod() != GET) {
        DecanterChannels.writeError(ctx, request, METHOD_NOT_ALLOWED);
        return;
    }

    final String subPath = path.substring(this.path.length());
    final String filePath = sanitizeUri(directory, subPath);
    if (filePath == null) {
        DecanterChannels.writeError(ctx, request, FORBIDDEN);
        return;
    }

    final File file = new File(filePath);
    if (file.isHidden() || !file.exists()) {
        DecanterChannels.writeError(ctx, request, NOT_FOUND);
        return;
    }

    if (!file.isFile()) {
        DecanterChannels.writeError(ctx, request, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.getHeaders().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && ifModifiedSince.length() != 0) {
        Date ifModifiedSinceDate = HttpHeaderValues.parseDate(ifModifiedSince);

        // Only compare up to the second because the datetime format we send
        // to the client does
        // not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            DecanterChannels.writeNotModified(ctx, request);
            return;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        DecanterChannels.writeError(ctx, request, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    // Add cache headers
    long timeMillis = System.currentTimeMillis();
    long expireMillis = timeMillis + HTTP_CACHE_SECONDS * 1000;
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    response.setHeader(CONTENT_TYPE, DecanterContentType.create(file));
    response.setHeader(CONTENT_LENGTH, String.valueOf(fileLength));
    response.setHeader(DATE, HttpHeaderValues.getCurrentDate());
    response.setHeader(EXPIRES, HttpHeaderValues.getDateString(expireMillis));
    response.setHeader(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
    response.setHeader(LAST_MODIFIED, HttpHeaderValues.getDateString(file.lastModified()));

    Channel ch = e.getChannel();

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

    // Write the content.
    ChannelFuture writeFuture;
    if (ch.getPipeline().get(SslHandler.class) != null) {
        // Cannot use zero-copy with HTTPS.
        writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = ch.write(region);
        writeFuture.addListener(new ChannelFutureProgressListener() {
            public void operationComplete(ChannelFuture future) {
                region.releaseExternalResources();
            }

            public void operationProgressed(ChannelFuture future, long amount, long current, long total) {
                System.out.printf("%s: %d / %d (+%d)%n", filePath, current, total, amount);
            }
        });
    }
}

From source file:com.haulmont.cuba.core.sys.LogControlImpl.java

@Override
public String getTail(String fileName) throws LogControlException {
    // security check, supported only valid file names
    fileName = FilenameUtils.getName(fileName);

    StringBuilder sb = new StringBuilder();
    RandomAccessFile randomAccessFile = null;
    try {/*from  w  w w. j a v a  2  s.  co  m*/
        File logFile = new File(logDir, fileName);
        if (!logFile.exists())
            throw new LogFileNotFoundException(fileName);

        randomAccessFile = new RandomAccessFile(logFile, "r");
        long lengthFile = randomAccessFile.length();
        if (lengthFile >= LOG_TAIL_AMOUNT_BYTES) {
            randomAccessFile.seek(lengthFile - LOG_TAIL_AMOUNT_BYTES);
            skipFirstLine(randomAccessFile);
        }
        while (randomAccessFile.read() != -1) {
            randomAccessFile.seek(randomAccessFile.getFilePointer() - 1);
            String line = readUtf8Line(randomAccessFile);
            if (line != null) {
                sb.append(line).append("\n");
            }
        }
    } catch (IOException e) {
        log.error("Error reading log file", e);
        throw new LogControlException("Error reading log file: " + fileName);
    } finally {
        if (randomAccessFile != null) {
            try {
                randomAccessFile.close();
            } catch (IOException ignored) {
            }
        }
    }
    return sb.toString();
}

From source file:com.qumasoft.qvcslib.CompareFilesWithApacheDiff.java

private CompareLineInfo[] buildLinesFromFile(File inFile) throws IOException {
    List<CompareLineInfo> lineInfoList = new ArrayList<>();
    RandomAccessFile randomAccessFile = new RandomAccessFile(inFile, "r");
    long fileLength = randomAccessFile.length();
    int startOfLineSeekPosition = 0;
    int currentSeekPosition = 0;
    byte character;
    while (currentSeekPosition < fileLength) {
        character = randomAccessFile.readByte();
        currentSeekPosition = (int) randomAccessFile.getFilePointer();
        if (character == '\n') {
            int endOfLine = (int) randomAccessFile.getFilePointer();
            byte[] buffer = new byte[endOfLine - startOfLineSeekPosition];
            randomAccessFile.seek(startOfLineSeekPosition);
            randomAccessFile.readFully(buffer);
            String line = new String(buffer, UTF8);
            CompareLineInfo lineInfo = new CompareLineInfo(startOfLineSeekPosition, createCompareLine(line));
            lineInfoList.add(lineInfo);//from ww w.ja v  a  2  s . c om
            startOfLineSeekPosition = endOfLine;
        }
    }
    // Add the final line which can happen if it doesn't end in a newline.
    if ((fileLength - startOfLineSeekPosition) > 0L) {
        byte[] buffer = new byte[(int) fileLength - startOfLineSeekPosition];
        randomAccessFile.seek(startOfLineSeekPosition);
        randomAccessFile.readFully(buffer);
        String line = new String(buffer, UTF8);
        CompareLineInfo lineInfo = new CompareLineInfo(startOfLineSeekPosition, createCompareLine(line));
        lineInfoList.add(lineInfo);
    }
    CompareLineInfo[] lineInfoArray = new CompareLineInfo[lineInfoList.size()];
    int i = 0;
    for (CompareLineInfo lineInfo : lineInfoList) {
        lineInfoArray[i++] = lineInfo;
    }
    return lineInfoArray;
}

From source file:jp.andeb.obbutil.ObbUtilMain.java

private static boolean doAdd(String[] args) {
    final CommandLine commandLine;
    try {/*from   ww  w  . j  av  a2 s.co  m*/
        final CommandLineParser parser = new GnuParser();
        commandLine = parser.parse(OPTIONS_FOR_ADD, args);
    } catch (MissingArgumentException e) {
        System.err.println("??????: " + e.getOption().getOpt());
        printUsage(PROGNAME);
        return false;
    } catch (MissingOptionException e) {
        System.err.println("??????: " + e.getMissingOptions());
        printUsage(PROGNAME);
        return false;
    } catch (UnrecognizedOptionException e) {
        System.err.println("????: " + e.getOption());
        printUsage(PROGNAME);
        return false;
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        printUsage(PROGNAME);
        return false;
    }

    final String pkgName = commandLine.getOptionValue(PACKAGE_NAME.getOpt());
    final String versionStr = commandLine.getOptionValue(OBB_VERSION.getOpt());
    final Integer version = toInteger(versionStr);
    if (version == null) {
        System.err.println("??????: " + versionStr);
        printUsage(PROGNAME);
        return false;
    }
    final boolean isOverlay = commandLine.hasOption(OVERLAY_FLAG.getOpt());
    final String saltStr = commandLine.getOptionValue(SALT.getOpt());
    final byte[] salt;
    if (saltStr == null) {
        salt = null;
    } else {
        salt = toByteArray(saltStr, ObbInfoV1.SALT_LENGTH);
        if (salt == null) {
            System.err.println("????: " + saltStr);
            printUsage(PROGNAME);
            return false;
        }
    }

    final String[] nonRecognizedArgs = commandLine.getArgs();
    if (nonRecognizedArgs.length == 0) {
        System.err.println("????????");
        printUsage(PROGNAME);
        return false;
    }
    if (nonRecognizedArgs.length != 1) {
        System.err.println("???????");
        printUsage(PROGNAME);
        return false;
    }

    final File targetFile = new File(nonRecognizedArgs[0]);
    final RandomAccessFile targetRaFile;
    try {
        targetRaFile = new RandomAccessFile(targetFile, "rw");
    } catch (FileNotFoundException e) {
        System.err.println("????: " + targetFile.getPath());
        return false;
    }
    try {
        try {
            final ObbInfoV1 info = ObbInfoV1.fromFile(targetRaFile);
            System.err.println(
                    "?? OBB ???????: " + info.toString());
            return false;
        } catch (IOException e) {
            System.err
                    .println("????????: " + targetFile.getPath());
            return false;
        } catch (NotObbException e) {
            // 
        }

        int flag = 0;
        if (isOverlay) {
            flag |= ObbInfoV1.FLAG_OVERLAY;
        }
        if (salt != null) {
            flag |= ObbInfoV1.FLAG_SALTED;
        }
        final ObbInfoV1 obbInfo = new ObbInfoV1(flag, salt, pkgName, version.intValue());
        final ByteBuffer obbInfoBytes = obbInfo.toBytes();
        // ???
        targetRaFile.setLength(targetRaFile.length() + obbInfoBytes.remaining());
        targetRaFile.seek(targetRaFile.length() - obbInfoBytes.remaining());
        targetRaFile.write(obbInfoBytes.array(), obbInfoBytes.arrayOffset(), obbInfoBytes.remaining());
    } catch (IOException e) {
        System.err.println("OBB ?????????: " + targetFile.getPath());
        return false;
    } finally {
        try {
            targetRaFile.close();
        } catch (IOException e) {
            System.err.println("OBB ?????????: " + targetFile.getPath());
            return false;
        }
    }
    System.err.println("OBB ??????????: " + targetFile.getPath());
    return true;
}

From source file:com.remobile.file.LocalFilesystem.java

@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
    File file = new File(filesystemPathForURL(inputURL));

    if (!file.exists()) {
        throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
    }/*w w w  . j a  v a2 s. c  o m*/

    RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
    try {
        if (raf.length() >= size) {
            FileChannel channel = raf.getChannel();
            channel.truncate(size);
            return size;
        }

        return raf.length();
    } finally {
        raf.close();
    }

}

From source file:com.kyne.webby.rtk.modules.WebbyRTKModule.java

public List<String> readConsoleLog(final LogMode logMode) {
    final List<String> logLines = new ArrayList<String>();
    String line = "";

    File logFile = null;//from  www.j  a va  2s.co  m
    if (logMode == LogMode.NEW) {
        logFile = new File("logs/latest.log");
    } else if (logMode == LogMode.OLD) {
        logFile = new File("server.log");
    } else {
        throw new UnsupportedOperationException("Unsupported log mode " + logMode);
    }

    if (!logFile.exists()) {
        LogHelper.error("Unable to find the log file at " + logFile.getAbsolutePath());
        return Arrays.asList("Unable to find the log file");
    }

    RandomAccessFile randomFile = null;
    try {
        randomFile = new RandomAccessFile(logFile, "r");
        final long linesToRead = 100;
        final long fileLength = randomFile.length();
        long startPosition = fileLength - (linesToRead * 100);
        if (startPosition < 0) {
            startPosition = 0;
        }
        randomFile.seek(startPosition);
        while ((line = randomFile.readLine()) != null) {
            logLines.add(line.replace("[0;30;22m", "").replace("[0;34;22m", "").replace("[0;32;22m", "")
                    .replace("[0;36;22m", "").replace("[0;31;22m", "").replace("[0;35;22m", "")
                    .replace("[0;33;22m", "").replace("[0;37;22m", "").replace("[0;30;1m", "")
                    .replace("[0;34;1m", "").replace("[0;32;1m", "").replace("[0;36;1m", "")
                    .replace("[0;31;1m", "").replace("[0;35;1m", "").replace("[0;33;1m", "")
                    .replace("[0;37;1m", "").replace("[m", "").replace("[5m", "").replace("[21m", "")
                    .replace("[9m", "").replace("[4m", "").replace("[3m", "").replace("[0;39m", "")
                    .replace("[0m", ""));

        }
    } catch (final IOException e) {
        LogHelper.error("Unable to read server.log", e);
    } finally {
        IOUtils.closeQuietly(randomFile);
    }
    return logLines;
}

From source file:edu.harvard.i2b2.patientMapping.ui.PatientIDConversionJFrame.java

private void append(RandomAccessFile f, String outString) throws IOException {
    try {/*from w w w . j  ava  2  s .  com*/
        f.seek(f.length());
        f.writeBytes(outString);
    } catch (IOException e) {
        throw new IOException("trouble writing to random access file.");
    }
    return;
}