Example usage for java.io RandomAccessFile setLength

List of usage examples for java.io RandomAccessFile setLength

Introduction

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

Prototype

public native void setLength(long newLength) throws IOException;

Source Link

Document

Sets the length of this file.

Usage

From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.BlockPoolSlice.java

/**
 * Find out the number of bytes in the block that match its crc.
 * <p/>/*  w w w  . j a va  2  s . c o m*/
 * This algorithm assumes that data corruption caused by unexpected
 * datanode shutdown occurs only in the last crc chunk. So it checks
 * only the last chunk.
 *
 * @param blockFile
 *     the block file
 * @param genStamp
 *     generation stamp of the block
 * @return the number of valid bytes
 */
private long validateIntegrityAndSetLength(File blockFile, long genStamp) {
    DataInputStream checksumIn = null;
    InputStream blockIn = null;
    try {
        final File metaFile = FsDatasetUtil.getMetaFile(blockFile, genStamp);
        long blockFileLen = blockFile.length();
        long metaFileLen = metaFile.length();
        int crcHeaderLen = DataChecksum.getChecksumHeaderSize();
        if (!blockFile.exists() || blockFileLen == 0 || !metaFile.exists() || metaFileLen < crcHeaderLen) {
            return 0;
        }
        checksumIn = new DataInputStream(
                new BufferedInputStream(new FileInputStream(metaFile), HdfsConstants.IO_FILE_BUFFER_SIZE));

        // read and handle the common header here. For now just a version
        BlockMetadataHeader header = BlockMetadataHeader.readHeader(checksumIn);
        short version = header.getVersion();
        if (version != BlockMetadataHeader.VERSION) {
            FsDatasetImpl.LOG
                    .warn("Wrong version (" + version + ") for metadata file " + metaFile + " ignoring ...");
        }
        DataChecksum checksum = header.getChecksum();
        int bytesPerChecksum = checksum.getBytesPerChecksum();
        int checksumSize = checksum.getChecksumSize();
        long numChunks = Math.min((blockFileLen + bytesPerChecksum - 1) / bytesPerChecksum,
                (metaFileLen - crcHeaderLen) / checksumSize);
        if (numChunks == 0) {
            return 0;
        }
        IOUtils.skipFully(checksumIn, (numChunks - 1) * checksumSize);
        blockIn = new FileInputStream(blockFile);
        long lastChunkStartPos = (numChunks - 1) * bytesPerChecksum;
        IOUtils.skipFully(blockIn, lastChunkStartPos);
        int lastChunkSize = (int) Math.min(bytesPerChecksum, blockFileLen - lastChunkStartPos);
        byte[] buf = new byte[lastChunkSize + checksumSize];
        checksumIn.readFully(buf, lastChunkSize, checksumSize);
        IOUtils.readFully(blockIn, buf, 0, lastChunkSize);

        checksum.update(buf, 0, lastChunkSize);
        long validFileLength;
        if (checksum.compare(buf, lastChunkSize)) { // last chunk matches crc
            validFileLength = lastChunkStartPos + lastChunkSize;
        } else { // last chunck is corrupt
            validFileLength = lastChunkStartPos;
        }

        // truncate if extra bytes are present without CRC
        if (blockFile.length() > validFileLength) {
            RandomAccessFile blockRAF = new RandomAccessFile(blockFile, "rw");
            try {
                // truncate blockFile
                blockRAF.setLength(validFileLength);
            } finally {
                blockRAF.close();
            }
        }

        return validFileLength;
    } catch (IOException e) {
        FsDatasetImpl.LOG.warn(e);
        return 0;
    } finally {
        IOUtils.closeStream(checksumIn);
        IOUtils.closeStream(blockIn);
    }
}

From source file:org.interreg.docexplore.authoring.AuthoringMenu.java

void writeRecent() {
    try {/*from  w w  w.  ja v  a  2s .c  o  m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(recent);
        oos.flush();
        RandomAccessFile file = new RandomAccessFile(new File(DocExploreTool.getHomeDir(), "ATRecent"), "rw");
        file.setLength(0);
        file.write(baos.toByteArray());
        file.close();
        oos.close();

        //         ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("ATRecent"), false));
        //         out.writeObject(recent);
        //         out.close();
    } catch (Exception e) {
        ErrorHandler.defaultHandler.submit(e, true);
    }
}

From source file:io.pcp.parfait.dxm.FileByteBufferFactory.java

public ByteBuffer build(int length) throws IOException {
    RandomAccessFile fos = null;
    try {/*  w w  w.j  a v a2 s . co  m*/
        File parent = file.getParentFile();
        if (parent == null) {
            throw new RuntimeException("Could not find parent of output file " + file.getCanonicalPath());
        } else if (parent.exists()) {
            file.delete(); /* directory update visible to MMV PMDA */
            if (file.exists()) {
                throw new RuntimeException("Could not delete existing file " + file.getCanonicalPath());
            }
        } else if (!parent.mkdirs()) {
            throw new RuntimeException("Could not create output directory " + parent.getCanonicalPath());
        }
        fos = new RandomAccessFile(file, "rw");
        fos.setLength(length);
        ByteBuffer tempDataFile = fos.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, length);
        tempDataFile.order(ByteOrder.nativeOrder());
        fos.close();

        return tempDataFile;
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}

From source file:com.roamtouch.menuserver.utils.FileUtils.java

private void removeLastCharacter(File fileName) {

    RandomAccessFile f;
    long length;//from w  w  w  .  j  ava  2s .c  om

    try {

        f = new RandomAccessFile(fileName, "rw");
        length = f.length();
        long l;

        if (length > 0)
            l = length - 1;
        else
            l = length;

        f.setLength(l);
        f.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:hudson.FilePathTest.java

private void checkTarUntarRoundTrip(String filePrefix, long fileSize) throws Exception {
    final File tmpDir = temp.newFolder(filePrefix);
    final File tempFile = new File(tmpDir, filePrefix + ".log");
    RandomAccessFile file = new RandomAccessFile(tempFile, "rw");
    final File tarFile = new File(tmpDir, filePrefix + ".tar");

    file.setLength(fileSize);
    assumeTrue(fileSize == file.length());
    file.close();/* w  w w  .  j  a  v  a 2s . c  o m*/

    // Compress archive
    final FilePath tmpDirPath = new FilePath(tmpDir);
    int tar = tmpDirPath.tar(new FileOutputStream(tarFile), tempFile.getName());
    assertEquals("One file should have been compressed", 1, tar);

    // Decompress
    FilePath outDir = new FilePath(temp.newFolder(filePrefix + "_out"));
    final FilePath outFile = outDir.child(tempFile.getName());
    tmpDirPath.child(tarFile.getName()).untar(outDir, TarCompression.NONE);
    assertEquals("Result file after the roundtrip differs from the initial file",
            new FilePath(tempFile).digest(), outFile.digest());
}

From source file:org.kchine.rpf.PoolUtils.java

public static void killLocalWinProcess(String processId, boolean isKILLSIG) throws Exception {

    String killpath = System.getProperty("java.io.tmpdir") + "/rpf/WinTools/" + "kill.exe";
    File killFile = new File(killpath);
    if (!killFile.exists()) {
        killFile.getParentFile().mkdirs();
        InputStream is = PoolUtils.class.getResourceAsStream("/wintools/kill.exe");
        RandomAccessFile raf = new RandomAccessFile(killFile, "rw");
        raf.setLength(0);
        int b;/*  w w  w . j  av  a  2  s.  co  m*/
        while ((b = is.read()) != -1)
            raf.write((byte) b);
        raf.close();
    }
    String[] command = new String[] { killpath, processId };
    Runtime rt = Runtime.getRuntime();
    final Process proc = rt.exec(command);

    final StringBuffer killPrint = new StringBuffer();
    final StringBuffer errorPrint = new StringBuffer();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getInputStream();
                int b;
                while ((b = is.read()) != -1) {
                    killPrint.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getErrorStream();
                int b;
                while ((b = is.read()) != -1) {
                    errorPrint.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    int exitVal = proc.waitFor();
    if (exitVal != 0)
        throw new Exception("kill exit code : " + exitVal + "\n" + errorPrint);
}

From source file:com.asakusafw.runtime.util.lock.LocalFileLockProvider.java

@Override
public LocalFileLockObject<T> tryLock(T target) throws IOException {
    if (baseDirectory.mkdirs() == false && baseDirectory.isDirectory() == false) {
        throw new IOException(MessageFormat.format("Failed to create lock directory: {0}", baseDirectory));
    }/*from   w ww  .  java2  s .  c  o m*/
    String fileName = String.format("%08x.lck", target == null ? -1 : target.hashCode()); //$NON-NLS-1$
    File lockFile = new File(baseDirectory, fileName);
    RandomAccessFile fd = new RandomAccessFile(lockFile, "rw"); //$NON-NLS-1$
    boolean success = false;
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug(MessageFormat.format("Start to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$
                    target, lockFile));
        }
        FileLock lockEntity = getLock(target, lockFile, fd);
        if (lockEntity == null) {
            return null;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Finished to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$
                        target, lockFile));
            }
            try {
                fd.seek(0L);
                fd.setLength(0L);
                fd.write(String.valueOf(target).getBytes(ENCODING));
                success = true;
                return new LocalFileLockObject<>(target, lockFile, fd, lockEntity);
            } finally {
                if (success == false) {
                    lockEntity.release();
                }
            }
        }
    } finally {
        if (success == false) {
            fd.close();
        }
    }
}

From source file:org.kchine.rpf.PoolUtils.java

public static String currentWinProcessID() throws Exception {

    String pslistpath = System.getProperty("java.io.tmpdir") + "/rpf/WinTools/" + "ps.exe";
    System.out.println(pslistpath);
    File pslistFile = new File(pslistpath);
    if (!pslistFile.exists()) {
        pslistFile.getParentFile().mkdirs();
        InputStream is = PoolUtils.class.getResourceAsStream("/wintools/ps.exe");
        RandomAccessFile raf = new RandomAccessFile(pslistFile, "rw");
        raf.setLength(0);
        int b;//from www  . j a v a2s . c  o  m
        while ((b = is.read()) != -1)
            raf.write((byte) b);
        raf.close();
    }
    String[] command = new String[] { pslistpath };
    Runtime rt = Runtime.getRuntime();
    final Process proc = rt.exec(command);
    final StringBuffer psPrint = new StringBuffer();
    final StringBuffer psError = new StringBuffer();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getInputStream();
                int b;
                while ((b = is.read()) != -1) {
                    psPrint.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getErrorStream();
                int b;
                while ((b = is.read()) != -1) {
                    psError.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    int exitVal = proc.waitFor();
    if (exitVal != 0)
        throw new Exception("ps exit code : " + exitVal);

    BufferedReader reader = new BufferedReader(new StringReader(psPrint.toString()));
    String line;
    int i = 0;
    while (!(line = reader.readLine()).startsWith("PID  PPID  THR PR NAME"))
        ++i;
    ++i;
    while ((line = reader.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(line, " ");
        st.nextElement();
        String PPID = (String) st.nextElement();
        st.nextElement();
        st.nextElement();
        if (line.endsWith("\\ps.exe"))
            return PPID;
        ++i;
    }
    return null;
}

From source file:org.apache.flume.channel.file.TestFileChannelRestart.java

private void doTestTruncatedCheckpointMeta(boolean backup) throws Exception {
    Map<String, String> overrides = Maps.newHashMap();
    overrides.put(FileChannelConfiguration.USE_DUAL_CHECKPOINTS, String.valueOf(backup));
    channel = createFileChannel(overrides);
    channel.start();//from w  w  w  .  jav  a2 s  . c  o m
    Assert.assertTrue(channel.isOpen());
    Set<String> in = putEvents(channel, "restart", 10, 100);
    Assert.assertEquals(100, in.size());
    forceCheckpoint(channel);
    if (backup) {
        Thread.sleep(2000);
    }
    channel.stop();
    File checkpoint = new File(checkpointDir, "checkpoint");
    RandomAccessFile writer = new RandomAccessFile(Serialization.getMetaDataFile(checkpoint), "rw");
    writer.setLength(0);
    writer.getFD().sync();
    writer.close();
    channel = createFileChannel(overrides);
    channel.start();
    Assert.assertTrue(channel.isOpen());
    Assert.assertTrue(!backup || channel.checkpointBackupRestored());
    Set<String> out = consumeChannel(channel);
    compareInputAndOut(in, out);
}

From source file:com.stimulus.archiva.domain.Volume.java

protected void writeVolumeInfoLines(RandomAccessFile out) {
    try {/* www . j a  v  a 2  s  .c om*/
        logger.debug("writeVolumeInfoLines()");
        out.setLength(0);
        out.seek(0);
        // don't save to ejected volume
        if (isEjected())
            return;

        // make a new volume unused
        if (getStatus() == Volume.Status.NEW)
            setStatus(Volume.Status.UNUSED);
        out.seek(0); //Seek to end of file
        out.writeBytes("# Archiva " + Config.getConfig().getApplicationVersion() + " Volume Information\n");
        out.writeBytes("# note: this file is crucial - do not delete it!\n");
        out.writeBytes("version:3\n");
        if (getID() != null || getID().length() > 0) {
            out.writeBytes("id:" + getID() + "\n");
        }
        if (getStatus() != null) {
            out.writeBytes("status:" + getStatus() + "\n");
        }
        if (getCreatedDate() != null)
            out.writeBytes("created:" + DateUtil.convertDatetoString(getCreatedDate()) + "\n");
        if (getClosedDate() != null)
            out.writeBytes("closed:" + DateUtil.convertDatetoString(getClosedDate()) + "\n");

    } catch (IOException io) {
        if (getStatus() != Volume.Status.UNMOUNTED)
            logger.error("failed to write volumeinfo. {" + toString() + "} cause:" + io, io);
    } catch (ConfigurationException ce) {
        logger.error("failed to set volume status. {" + toString() + "} cause:" + ce, ce);
    }
}