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.xzjmt.util.ipseek.IPSeeker.java

public void init() {
    ipCache = new Hashtable<String, IPLocation>();
    loc = new IPLocation();
    buf = new byte[100];
    b4 = new byte[4];
    b3 = new byte[3];
    try {//  ww  w.  j  a va 2  s  .c  om
        String basePath = realPathResolver.get("/");
        if (!basePath.endsWith("/")) {
            basePath += File.separator;
        }
        String file = basePath + filename;
        ipFile = new RandomAccessFile(file, "r");
    } catch (Exception e) {
        log.info("IP??IP");
        ipFile = null;
    }
    // ???
    if (ipFile != null) {
        try {
            ipBegin = readLong4(0);
            ipEnd = readLong4(4);
            if (ipBegin == -1 || ipEnd == -1) {
                ipFile.close();
                ipFile = null;
            }
        } catch (Exception e) {
            log.info("IP???IP");
            this.closeIpFile();
        }
    }
}

From source file:com.alibaba.otter.node.etl.common.pipe.impl.http.AbstractHttpPipe.java

protected EncryptedData encryptFile(File file) {
    // ?file path??
    EncryptedData encryptedData = null;//from  w w  w .j  av a  2s .com
    try {
        encryptedData = EncryptUtils.encrypt(file.getPath().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        // ignore
    }

    // ?
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(file, "rw");
        long origLength = file.length();
        int keyLength = ByteUtils.stringToBytes(encryptedData.getKey()).length;
        int crcLength = ByteUtils.stringToBytes(encryptedData.getCrc()).length;
        long totalLength = origLength + crcLength + keyLength;
        raf.setLength(totalLength);
        raf.seek(origLength);
        raf.write(ByteUtils.stringToBytes(encryptedData.getKey()), 0, keyLength);
        raf.seek(origLength + keyLength);
        raf.write(ByteUtils.stringToBytes(encryptedData.getCrc()), 0, crcLength);
    } catch (Exception e) {
        throw new PipeException("write_encrypted_error", e);
    } finally {
        IOUtils.closeQuietly(raf);
    }

    return encryptedData;
}

From source file:com.frostwire.transfers.YouTubeDownload.java

private static void removeUdta(File mp4) throws IOException {
    RandomAccessFile f = new RandomAccessFile(mp4, "rw");
    try {//  w  w w  .j a v a 2s.c  o  m
        IsoFile.free(f, Box.udta, ByteBuffer.allocate(100 * 1024));
    } finally {
        IOUtils.closeQuietly(f);
    }
}

From source file:org.fhaes.fhfilechecker.FrameViewOutput.java

public PrintListingPainter(String file) {

    fileName = file;//from   w ww .  j  a  v a  2 s .co m
    try {
        // Open file
        raf = new RandomAccessFile(file, "r");
    } catch (Exception e) {
        rememberedEOF = true;
    }
}

From source file:com.abiquo.appliancemanager.ApplianceManagerAsserts.java

protected static File createUploadTempFile() throws IOException {
    Random rnd = new Random(System.currentTimeMillis());
    final String fileName = String.valueOf(rnd.nextLong());
    File file = File.createTempFile(fileName, ".uploadTest");

    RandomAccessFile f = new RandomAccessFile(file, "rw");
    f.setLength(UPLOAD_FILE_SIZE_BYTES);

    file.deleteOnExit();// ww  w.  ja  v  a 2  s .co m

    return file;
}

From source file:com.aliyun.oss.integrationtests.TestUtils.java

public static String genRandomLengthFile() throws IOException {
    ensureDirExist(TestBase.UPLOAD_DIR);
    String filePath = TestBase.UPLOAD_DIR + System.currentTimeMillis();
    RandomAccessFile raf = new RandomAccessFile(filePath, "rw");
    FileChannel fc = raf.getChannel();

    long fileLength = rand.nextInt(MAX_RANDOM_LENGTH);
    MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, fileLength);
    try {/*from   w  w  w .  j a  va  2  s. c  o  m*/
        for (int i = 0; i < fileLength; i++) {
            mbb.put(pickupAlphabet());
        }
        return filePath;
    } finally {
        if (fc != null) {
            fc.close();
        }

        if (raf != null) {
            raf.close();
        }
    }
}

From source file:ar.com.qbe.siniestros.model.utils.MimeMagic.MagicMatcher.java

/**
 * test to see if this match or any submatches match
 *
 * @param f the file that should be used to test the match
 * @param onlyMimeMatch DOCUMENT ME!/*from   www  .  j a v a  2 s .  co m*/
 *
 * @return the deepest magic match object that matched
 *
 * @throws IOException DOCUMENT ME!
 * @throws UnsupportedTypeException DOCUMENT ME!
 */
public MagicMatch test(File f, boolean onlyMimeMatch) throws IOException, UnsupportedTypeException {
    log.debug("test(File)");

    int offset = match.getOffset();
    String description = match.getDescription();
    String type = match.getType();
    String mimeType = match.getMimeType();

    log.debug("test(File): testing '" + f.getName() + "' for '" + description + "'");

    log.debug("test(File): \n=== BEGIN MATCH INFO ==");
    log.debug(match.print());
    log.debug("test(File): \n=== END MATCH INFO ====\n");

    RandomAccessFile file = null;
    file = new RandomAccessFile(f, "r");

    try {
        int length = 0;

        if (type.equals("byte")) {
            length = 1;
        } else if (type.equals("short") || type.equals("leshort") || type.equals("beshort")) {
            length = 4;
        } else if (type.equals("long") || type.equals("lelong") || type.equals("belong")) {
            length = 8;
        } else if (type.equals("string")) {
            length = match.getTest().capacity();
        } else if (type.equals("regex")) {

            final int matchLength = match.getLength();
            length = (matchLength == 0) ? (int) file.length() - offset : matchLength;

            if (length < 0) {
                length = 0;
            }
        } else if (type.equals("detector")) {
            length = (int) file.length() - offset;

            if (length < 0) {
                length = 0;
            }
        } else {
            throw new UnsupportedTypeException("unsupported test type '" + type + "'");
        }

        // we know this match won't work since there isn't enough data for the test
        if (length > (file.length() - offset)) {
            return null;
        }

        byte[] buf = new byte[length];
        file.seek(offset);

        int bytesRead = 0;
        int size = 0;
        boolean gotAllBytes = false;
        boolean done = false;

        while (!done) {
            size = file.read(buf, 0, length - bytesRead);

            if (size == -1) {
                throw new IOException("reached end of file before all bytes were read");
            }

            bytesRead += size;

            if (bytesRead == length) {
                gotAllBytes = true;
                done = true;
            }
        }

        log.debug("test(File): stream size is '" + buf.length + "'");

        MagicMatch match = null;
        MagicMatch submatch = null;

        if (testInternal(buf)) {
            // set the top level match to this one
            try {
                match = getMatch() != null ? (MagicMatch) getMatch().clone() : null;
            } catch (CloneNotSupportedException e) {
                // noop
            }

            log.debug("test(File): testing matched '" + description + "'");

            // set the data on this match
            if ((onlyMimeMatch == false) && (subMatchers != null) && (subMatchers.size() > 0)) {
                log.debug(
                        "test(File): testing " + subMatchers.size() + " submatches for '" + description + "'");

                for (int i = 0; i < subMatchers.size(); i++) {
                    log.debug("test(File): testing submatch " + i);

                    MagicMatcher m = (MagicMatcher) subMatchers.get(i);

                    if ((submatch = m.test(f, false)) != null) {
                        log.debug("test(File): submatch " + i + " matched with '" + submatch.getDescription()
                                + "'");
                        match.addSubMatch(submatch);
                    } else {
                        log.debug("test(File): submatch " + i + " doesn't match");
                    }
                }
            }
        }

        return match;
    } finally {
        try {
            file.close();
        } catch (Exception fce) {
        }
    }
}

From source file:com.topsem.common.net.IPSeeker.java

public IPSeeker(File ipFile) throws Exception {
    this.ipFile = new RandomAccessFile(ipFile, "r");
    ipCache = new HashMap<String, IPLocation>();
    FileChannel fc = this.ipFile.getChannel();
    mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, ipFile.length());
    mbb.order(ByteOrder.LITTLE_ENDIAN);
    ipBegin = readInt(0);//ww w.j  a v a 2  s .c  o  m
    ipEnd = readInt(4);
    if (ipBegin == -1 || ipEnd == -1) {
        throw new IOException("IP???IP");
    }
    log.debug("IP?:" + ipFile.getAbsolutePath());
}

From source file:com.almende.eve.state.file.ConcurrentJsonFileState.java

/**
 * Open file./*  w ww .  java2  s  . co  m*/
 * 
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@SuppressWarnings("resource")
protected void openFile() throws IOException {
    Lock llock = null;
    synchronized (LOCKED) {
        llock = LOCKED.get(filename);
        if (llock == null) {
            llock = new Lock();
            LOCKED.put(filename, llock);
        }
    }
    synchronized (llock) {
        while (llock.locked) {
            try {
                llock.wait();
            } catch (final InterruptedException e) {
            }
        }
        llock.locked = true;

        final File file = new File(filename);
        if (!file.exists()) {
            llock.locked = false;
            llock.notifyAll();
            throw new IllegalStateException("Warning: File doesn't exist (anymore):'" + filename + "'");
        }

        channel = new RandomAccessFile(file, "rw").getChannel();
        try {
            // TODO: add support for shared locks, allowing parallel reading
            // operations.
            lock = channel.lock();

        } catch (final Exception e) {
            channel.close();
            channel = null;
            lock = null;
            llock.locked = false;
            llock.notifyAll();
            throw new IllegalStateException("error, couldn't obtain file lock on:" + filename, e);
        }
        fis = new BufferedInputStream(Channels.newInputStream(channel));
        fos = new BufferedOutputStream(Channels.newOutputStream(channel));
    }
}

From source file:com.btoddb.fastpersitentqueue.JournalFileTest.java

@Test
public void testInvalidHeaderVersion() throws Exception {
    JournalFile jf1 = new JournalFile(theFile);
    jf1.initForWriting(new UUID());
    jf1.close();//from ww w  .  j  a  v a  2s.  co  m

    // mess up the UUID
    RandomAccessFile raFile = new RandomAccessFile(theFile, "rw");
    Utils.writeInt(raFile, 2);
    raFile.close();
    //        Utils.writeUuidToFile(raFile, id);
    //        Utils.writeLong(raFile, numberOfEntries.get());

    JournalFile jf2 = new JournalFile(theFile);
    try {
        jf2.initForReading();
        fail("should have found invalid journal version");
    } catch (FpqException e) {
        assertThat(e.getMessage(), containsString("invalid journal file version"));
    }
}