Example usage for java.io RandomAccessFile RandomAccessFile

List of usage examples for java.io RandomAccessFile RandomAccessFile

Introduction

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

Prototype

public RandomAccessFile(File file, String mode) throws FileNotFoundException 

Source Link

Document

Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.

Usage

From source file:com.datatorrent.lib.io.fs.TailFsInputOperator.java

private String readLine() throws IOException {
    StringBuffer sb = new StringBuffer();
    char readChar;
    int ch;/*from   w  w  w. ja v a 2 s .  co m*/
    long pos = reader.getFilePointer();
    long length = file.length();
    if ((length < pos) || (length == pos && FileUtils.isFileNewer(file, accessTime))) {
        // file got rotated or truncated
        reader.close();
        reader = new RandomAccessFile(file, "r");
        position = 0;
        reader.seek(position);
        pos = 0;
    }
    accessTime = System.currentTimeMillis();
    while ((ch = reader.read()) != -1) {
        readChar = (char) ch;
        if (readChar != delimiter) {
            sb.append(readChar);
        } else {
            return sb.toString();
        }
    }
    reader.seek(pos);
    return null;
}

From source file:jm.web.Archivo.java

public String getArchivo(String path, int clave) {
    this._archivoNombre = "";
    try {// w  w  w . j ava  2 s  .  c  o  m
        ResultSet res = this.consulta("select * from tbl_archivo where id_archivo=" + clave + ";");
        if (res.next()) {
            this._archivoNombre = (res.getString("nombre") != null) ? res.getString("nombre") : "";
            try {
                this._archivo = new File(path, this._archivoNombre);
                if (!this._archivo.exists()) {
                    byte[] bytes = (res.getString("archivo") != null) ? res.getBytes("archivo") : null;
                    RandomAccessFile archivo = new RandomAccessFile(path + this._archivoNombre, "rw");
                    archivo.write(bytes);
                    archivo.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            res.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this._archivoNombre;
}

From source file:com.moviejukebox.scanner.BDRipScanner.java

public BDPlaylistInfo getBDPlaylistInfo(String filePath) throws IOException {

    BDPlaylistInfo ret = new BDPlaylistInfo();
    ret.duration = 0;/*ww  w  .  j a  v  a2 s .c o  m*/

    byte[] data;
    /* Some ported code from the bdinfo free project */
    try ( /* The input stream... */RandomAccessFile fileReader = new RandomAccessFile(filePath, "r")) {
        /* Some ported code from the bdinfo free project */
        data = new byte[(int) fileReader.length()];
        int dataLength = fileReader.read(data, 0, data.length);
        LOG.trace("Read data length: {}", dataLength);
    }

    byte[] fileType = new byte[8];
    System.arraycopy(data, 0, fileType, 0, fileType.length);

    String fileTypeString = new String(fileType);
    if (("MPLS0100".equals(fileTypeString) && "MPLS0200".equals(fileTypeString)) /*|| data[45] != 1*/) {
        LOG.info("Invalid playlist file {}", fileTypeString);
        return ret;
    }

    int playlistIndex = ((data[8] & 0xFF) << 24) + ((data[9] & 0xFF) << 16) + ((data[10] & 0xFF) << 8)
            + (data[11]);

    int playlistLength = data.length - playlistIndex - 4;
    int playlistLengthCorrect = ((data[playlistIndex] & 0xFF) << 24) + ((data[playlistIndex + 1] & 0xFF) << 16)
            + ((data[playlistIndex + 2] & 0xFF) << 8) + ((data[playlistIndex + 3] & 0xFF));
    LOG.trace("Playlist Length Correct: {}", playlistLengthCorrect);

    byte[] playlistData = new byte[playlistLength];
    System.arraycopy(data, playlistIndex + 4, playlistData, 0, playlistData.length);

    @SuppressWarnings("cast")
    int streamFileCount = (((playlistData[2] & 0xFF) << 8) + ((int) playlistData[3] & 0xFF));

    ret.streamList = new String[streamFileCount];

    int streamFileOffset = 6;
    for (int streamFileIndex = 0; streamFileIndex < streamFileCount; streamFileIndex++) {
        byte[] streamFileNameData = new byte[5];
        System.arraycopy(playlistData, streamFileOffset + 2, streamFileNameData, 0, streamFileNameData.length);

        String streamFile = new String(streamFileNameData) + ".M2TS";

        long timeIn = (((long) playlistData[streamFileOffset + 14] & 0xFF) << 24)
                + (((long) playlistData[streamFileOffset + 15] & 0xFF) << 16)
                + (((long) playlistData[streamFileOffset + 16] & 0xFF) << 8)
                + ((long) playlistData[streamFileOffset + 17] & 0xFF);

        long timeOut = (((long) playlistData[streamFileOffset + 18] & 0xFF) << 24)
                + (((long) playlistData[streamFileOffset + 19] & 0xFF) << 16)
                + (((long) playlistData[streamFileOffset + 20] & 0xFF) << 8)
                + ((long) playlistData[streamFileOffset + 21] & 0xFF);

        long length = (timeOut - timeIn) / 45000;

        // Process this movie stream
        if (streamFileIndex == 0 || !ret.streamList[streamFileIndex - 1].equals(streamFile)) {
            ret.duration += (int) length;
        }
        ret.streamList[streamFileIndex] = streamFile;

        streamFileOffset += 2 + ((playlistData[streamFileOffset] & 0xFF) << 8)
                + ((playlistData[streamFileOffset + 1] & 0xFF));
    }

    return ret;
}

From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java

/**
 * Reads the last line of the specified file.
 *
 * @param file//from ww w .  jav  a  2  s .c o m
 *       the file
 * @param charset
 *       the charset
 */
public static String readLastLine(final File file, final Charset charset) {
    try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
        long length = raf.length() - 1;

        ByteArrayOutputStream baos = new ByteArrayOutputStream(80);

        for (long pos = length; pos != -1; --pos) { // we start from the end of the file
            raf.seek(pos);

            int readByte = raf.readByte();

            if (readByte == 10) { // this is the case if the file ends with a line-break
                if (pos == length) {
                    continue;
                }
                break;
            } else if (readByte == 13) { // this is the case if the file ends with a line-break (Windows only)
                if (pos == length - 1) {
                    continue;
                }
                break;
            }

            baos.write(readByte);
        }

        byte[] bytes = baos.toByteArray();

        // reverse array because it was filled backwards
        ArrayUtils.reverse(bytes);

        // turn into string respecting the charset
        return new String(bytes, charset);
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}

From source file:com.ettrema.zsync.UploadReader.java

/**
 * Inserts the data from each DataRange into the output File, at the appropriate offset
 * //from  w w  w .  java2s  .c  om
 * @param byteRanges The Enumeration of Range/InputStream pairs parsed from the Upload's dataStream
 * @param outFile The output File being assembled
 * @throws IOException
 */
public static void sendRanges(Enumeration<ByteRange> byteRanges, File outFile) throws IOException {

    int BUFFER_SIZE = 16384;
    byte[] buffer = new byte[BUFFER_SIZE];

    RandomAccessFile randAccess = null;
    try {

        randAccess = new RandomAccessFile(outFile, "rw");
        while (byteRanges.hasMoreElements()) {

            ByteRange byteRange = byteRanges.nextElement();
            Range range = byteRange.getRange();
            InputStream data = byteRange.getDataQueue();

            sendBytes(data, range, buffer, randAccess);
        }
    } finally {
        Util.close(randAccess);
    }
}

From source file:com.temenos.interaction.loader.properties.ReloadablePropertiesFactoryBean.java

private List<Resource> getLastChangeAndClear(File f) {
    File lastChangeFileLock = new File(f.getParent(), ".lastChangeLock");
    List<Resource> ret = new ArrayList<>();
    /*/*from   w  w  w  .ja  va 2  s. c om*/
     * Maintain a specific lock to avoid partial file locking.
     */
    try (FileChannel fcLock = new RandomAccessFile(lastChangeFileLock, "rw").getChannel()) {

        try (FileLock lock = fcLock.lock()) {

            try (FileChannel fc = new RandomAccessFile(f, "rws").getChannel()) {

                try (BufferedReader bufR = new BufferedReader(new FileReader(f))) {
                    String sLine = null;
                    boolean bFirst = true;
                    while ((sLine = bufR.readLine()) != null) {
                        if (bFirst) {
                            if (sLine.startsWith("RefreshAll")) {
                                ret = null;
                                break;
                            }
                            bFirst = false;
                        }
                        Resource toAdd = new FileSystemResource(new File(sLine));
                        if (!ret.contains(toAdd)) {
                            ret.add(toAdd);
                        }
                    }
                    /*
                     * Empty the file
                     */
                    fc.truncate(0);
                }
            }
        }
    } catch (Exception e) {
        logger.error("Failed to get the lastChanges contents.", e);
    }

    return ret;
}

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;/*from w  w w  .j a v  a2 s.c om*/
    }

    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:app.utils.ACache.java

public byte[] getAsBinary(String key) {
    RandomAccessFile RAFile = null;
    boolean removeFile = false;
    try {/*from w  w  w .  j  a v  a  2 s  .c o m*/
        File file = mCache.get(key);
        if (!file.exists())
            return null;
        RAFile = new RandomAccessFile(file, "r");
        byte[] byteArray = new byte[(int) RAFile.length()];
        RAFile.read(byteArray);
        if (!Utils.isDue(byteArray)) {
            return Utils.clearDateInfo(byteArray);
        } else {
            removeFile = true;
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (RAFile != null) {
            try {
                RAFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (removeFile)
            remove(key);
    }
}

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void testReadByte() throws Exception {
    RandomAccessFile ra = new RandomAccessFile(logfile, "r");
    LineReader lr = new LineReader(logfile, "r");
    int counter = 1;
    while (!lr.eof()) {
        assertEquals("Byte #" + counter++ + " should be read correct", ra.readByte(), lr.readByte());
    }//from  w  w w  .j  a v  a2s. c  om
    ra.close();
    lr.close();
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.FileContentReaderDynamic.java

@Override
protected ReadableByteChannel getDirectReadableChannel() throws ContentIOException {
    try {/*ww  w .  j a v  a  2 s.c o m*/
        // the file must exist
        if (!file.exists()) {
            throw new IOException("File does not exist: " + file);
        }
        // create the channel
        ReadableByteChannel channel = null;
        if (allowRandomAccess) {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); // won't create it
            channel = randomAccessFile.getChannel();
        } else {
            InputStream is = new FileInputStream(file);
            channel = Channels.newChannel(is);
        }
        // done
        if (logger.isDebugEnabled()) {
            logger.debug("Opened write channel to file: \n" + "   file: " + file + "\n" + "   random-access: "
                    + allowRandomAccess);
        }
        return channel;
    } catch (Throwable e) {
        throw new ContentIOException("Failed to open file channel: " + this, e);
    }
}