Example usage for java.nio.channels FileChannel truncate

List of usage examples for java.nio.channels FileChannel truncate

Introduction

In this page you can find the example usage for java.nio.channels FileChannel truncate.

Prototype

public abstract FileChannel truncate(long size) throws IOException;

Source Link

Document

Truncates this channel's file to the given size.

Usage

From source file:com.streamsets.pipeline.stage.origin.logtail.TestFileTailSource.java

@Test
public void testFileTruncatedBetweenRuns() throws Exception {
    File testDataDir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(testDataDir.mkdirs());
    File file = new File(testDataDir, "file.txt-1");
    Files.write(file.toPath(), Arrays.asList("A", "B", "C"), StandardCharsets.UTF_8);

    FileInfo fileInfo = new FileInfo();
    fileInfo.fileFullPath = testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}";
    fileInfo.fileRollMode = FileRollMode.PATTERN;
    fileInfo.firstFile = "";
    fileInfo.patternForToken = "[0-9]";
    Source source = createSourceForPeriodicFile(testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}",
            "[0-9]");
    SourceRunner runner = createRunner(source);
    try {/*from   w ww  .jav a2s.  c om*/
        // run till current end and stop pipeline
        runner.runInit();
        StageRunner.Output output = runner.runProduce(null, 10);
        Assert.assertEquals(3, output.getRecords().get("lane").size());
        runner.runDestroy();

        // truncate file
        FileChannel channel = new FileOutputStream(file, true).getChannel();
        channel.truncate(2);
        channel.close();

        // run again, no new data, no error
        source = createSourceForPeriodicFile(testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}", "[0-9]");
        runner = createRunner(source);
        runner.runInit();
        output = runner.runProduce(output.getNewOffset(), 10);
        Assert.assertEquals(0, output.getRecords().get("lane").size());
        runner.runDestroy();

        file = new File(testDataDir, "file.txt-2");
        Files.write(file.toPath(), Arrays.asList("A", "B"), StandardCharsets.UTF_8);

        // run again, new file
        source = createSourceForPeriodicFile(testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}", "[0-9]");
        runner = createRunner(source);
        runner.runInit();
        output = runner.runProduce(output.getNewOffset(), 10);
        Assert.assertEquals(2, output.getRecords().get("lane").size());

    } finally {
        runner.runDestroy();
    }
}

From source file:com.healthmarketscience.jackcess.Database.java

/**
 * Create a new Database for the given fileFormat
 * @param fileFormat version of new database.
 * @param mdbFile Location to write the new database to.  <b>If this file
 *    already exists, it will be overwritten.</b>
 * @param autoSync whether or not to enable auto-syncing on write.  if
 *                 {@code true}, writes will be immediately flushed to disk.
 *                 This leaves the database in a (fairly) consistent state
 *                 on each write, but can be very inefficient for many
 *                 updates.  if {@code false}, flushing to disk happens at
 *                 the jvm's leisure, which can be much faster, but may
 *                 leave the database in an inconsistent state if failures
 *                 are encountered during writing.
 * @param charset Charset to use, if {@code null}, uses default
 * @param timeZone TimeZone to use, if {@code null}, uses default
 * @usage _intermediate_method_/*w w  w .j  a v  a 2s.  c o  m*/
 */
public static Database create(FileFormat fileFormat, File mdbFile, boolean autoSync, Charset charset,
        TimeZone timeZone) throws IOException {
    if (fileFormat.getJetFormat().READ_ONLY) {
        throw new IOException("jet format '" + fileFormat.getJetFormat() + "' does not support writing");
    }

    FileChannel channel = openChannel(mdbFile, false);
    channel.truncate(0);
    transferFrom(channel, getResourceAsStream(fileFormat._emptyFile));
    channel.force(true);
    return new Database(mdbFile, channel, autoSync, fileFormat, charset, timeZone, null);
}

From source file:com.healthmarketscience.jackcess.impl.DatabaseImpl.java

/**
 * Create a new Database for the given fileFormat
 * @param fileFormat version of new database.
 * @param mdbFile Location to write the new database to.  <b>If this file
 *                already exists, it will be overwritten.</b>
 * @param channel  pre-opened FileChannel.  if provided explicitly, it will
 *                 not be closed by this Database instance
 * @param autoSync whether or not to enable auto-syncing on write.  if
 *                 {@code true}, writes will be immediately flushed to disk.
 *                 This leaves the database in a (fairly) consistent state
 *                 on each write, but can be very inefficient for many
 *                 updates.  if {@code false}, flushing to disk happens at
 *                 the jvm's leisure, which can be much faster, but may
 *                 leave the database in an inconsistent state if failures
 *                 are encountered during writing.  Writes may be flushed at
 *                 any time using {@link #flush}.
 * @param charset  Charset to use, if {@code null}, uses default
 * @param timeZone TimeZone to use, if {@code null}, uses default
 * @usage _advanced_method_//from w  w w. ja va  2s  . c  o  m
 */
public static DatabaseImpl create(FileFormat fileFormat, File mdbFile, FileChannel channel, boolean autoSync,
        Charset charset, TimeZone timeZone) throws IOException {
    FileFormatDetails details = getFileFormatDetails(fileFormat);
    if (details.getFormat().READ_ONLY) {
        throw new IOException("file format " + fileFormat + " does not support writing");
    }

    boolean closeChannel = false;
    if (channel == null) {
        channel = openChannel(mdbFile, false);
        closeChannel = true;
    }

    boolean success = false;
    try {
        channel.truncate(0);
        transferFrom(channel, getResourceAsStream(details.getEmptyFilePath()));
        channel.force(true);
        DatabaseImpl db = new DatabaseImpl(mdbFile, channel, closeChannel, autoSync, fileFormat, charset,
                timeZone, null);
        success = true;
        return db;
    } finally {
        if (!success && closeChannel) {
            // something blew up, shutdown the channel (quietly)
            ByteUtil.closeQuietly(channel);
        }
    }
}

From source file:com.yobidrive.diskmap.needles.NeedleManager.java

private void truncate(NeedlePointer needlePointer) throws NeedleManagerException {
    // Truncate current file
    if (needlePointer.getNeedleOffset() < 0) {
        logger.error("Request for truncating " + needlePointer.toString() + "!!!");
        throw new NeedleManagerException("Request for truncating " + needlePointer.toString() + "!!!");
    }/*from  ww w.ja va2  s  .co  m*/
    // truncates current file
    FileChannel fc = getChannel(needlePointer.getNeedleFileNumber());
    if (fc == null) {
        logger.error("Request for truncating " + needlePointer.toString() + ", no File Channel!!!");
        throw new NeedleManagerException(
                "Request for truncating " + needlePointer.toString() + ", no File Channel!!!");
    }
    try {
        fc.truncate(needlePointer.getNeedleOffset());
        fc.force(true);
    } catch (IOException ie) {
        logger.error("Error truncating " + needlePointer.toString(), ie);
        throw new NeedleManagerException("Error truncating " + needlePointer.toString(), ie);
    }
    // Removes subsequent files. In fact just rename them and alert via logger
    int logNumber = needlePointer.getNeedleFileNumber() + 1;
    while (channelMap.contains(new Integer(logNumber))) {
        closeChannel(logNumber);
        File toClose = getFile(logNumber);
        if (toClose != null) {
            try {
                toClose.renameTo(new File(toClose.getCanonicalFile() + ".bak"));
            } catch (IOException ie) {
                throw new NeedleManagerException(
                        "Could not rename to .bak for file number " + Integer.toHexString(logNumber));
            }
        }
        logNumber++;
    }
}

From source file:com.clustercontrol.agent.job.PublicKeyThread.java

/**
 *  ?Authorized_key????<BR>/*from  www . ja  va  2s. c  o m*/
 * 
 * @param publicKey
 * @return true : ?false:
 */
private synchronized boolean deleteKey(String publicKey) {
    m_log.debug("delete key start");

    if (SKIP_KEYFILE_UPDATE) {
        m_log.info("skipped deleting publicKey");
        return true;
    }

    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    CharsetDecoder decoder = charset.newDecoder();

    //???
    String fileName = AgentProperties.getProperty(execUser.toLowerCase() + AUTHORIZED_KEY_PATH);
    if (fileName == null || fileName.length() == 0)
        return false;

    //File?
    File fi = new File(fileName);

    RandomAccessFile randomAccessFile = null;
    FileChannel channel = null;
    FileLock lock = null;
    boolean delete = false;
    try {
        //RandomAccessFile?
        randomAccessFile = new RandomAccessFile(fi, "rw");
        //FileChannel?
        channel = randomAccessFile.getChannel();

        // 
        for (int i = 0; i < (FILELOCK_TIMEOUT / FILELOCK_WAIT); i++) {
            if (null != (lock = channel.tryLock())) {
                break;
            }
            m_log.info("waiting for locked file... [" + (i + 1) + "/" + (FILELOCK_TIMEOUT / FILELOCK_WAIT)
                    + " : " + fileName + "]");
            Thread.sleep(FILELOCK_WAIT);
        }
        if (null == lock) {
            m_log.warn("file locking timeout.");
            return false;
        }

        // (?)
        synchronized (authKeyLock) {
            //??
            ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());

            //??
            channel.read(buffer);

            // ???????????0?
            buffer.flip();

            //??
            String contents = decoder.decode(buffer).toString();

            // ?
            m_log.debug("contents " + contents.length() + " : " + contents);

            //??
            List<String> keyCheck = new ArrayList<String>();
            StringTokenizer tokenizer = new StringTokenizer(contents, "\n");
            while (tokenizer.hasMoreTokens()) {
                keyCheck.add(tokenizer.nextToken());
            }

            //??????
            int s = keyCheck.lastIndexOf(publicKey);
            if (s != -1) {
                // ?
                m_log.debug("remobe key : " + keyCheck.get(s));
                keyCheck.remove(s);
            }

            //?????
            encoder.reset();
            buffer.clear();

            int i;
            if (keyCheck.size() > 0) {
                for (i = 0; i < keyCheck.size() - 1; i++) {
                    encoder.encode(CharBuffer.wrap(keyCheck.get(i) + "\n"), buffer, false);
                }
                encoder.encode(CharBuffer.wrap(keyCheck.get(i)), buffer, true);
            }

            //???
            buffer.flip();
            channel.truncate(0);
            channel.position(0);
            channel.write(buffer);
        }

        delete = true;
    } catch (IOException e) {
        m_log.error(e.getMessage(), e);
    } catch (RuntimeException e) {
        m_log.error(e.getMessage(), e);
    } catch (InterruptedException e) {
        m_log.error(e.getMessage(), e);
    } finally {
        try {
            if (channel != null) {
                channel.close();
            }
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
            //?
            if (lock != null) {
                lock.release();
            }
        } catch (Exception e) {
        }
    }

    return delete;
}

From source file:org.alfresco.repo.search.impl.lucene.index.IndexInfo.java

private void writeStatusToFile(FileChannel channel) throws IOException {
    long size = getBufferSize();

    ByteBuffer buffer;//  w ww.  j av a  2 s .c  om
    if (useNIOMemoryMapping) {
        MappedByteBuffer mbb = channel.map(MapMode.READ_WRITE, 0, size);
        mbb.load();
        buffer = mbb;
    } else {
        channel.truncate(size);
        buffer = ByteBuffer.wrap(new byte[(int) size]);
    }

    buffer.position(0);

    buffer.putLong(version);
    CRC32 crc32 = new CRC32();
    crc32.update((int) (version >>> 32) & 0xFFFFFFFF);
    crc32.update((int) (version >>> 0) & 0xFFFFFFFF);

    buffer.putInt(indexEntries.size());
    crc32.update(indexEntries.size());

    for (IndexEntry entry : indexEntries.values()) {
        String entryType = entry.getType().toString();
        writeString(buffer, crc32, entryType);

        writeString(buffer, crc32, entry.getName());

        writeString(buffer, crc32, entry.getParentName());

        String entryStatus = entry.getStatus().toString();
        writeString(buffer, crc32, entryStatus);

        writeString(buffer, crc32, entry.getMergeId());

        buffer.putLong(entry.getDocumentCount());
        crc32.update((int) (entry.getDocumentCount() >>> 32) & 0xFFFFFFFF);
        crc32.update((int) (entry.getDocumentCount() >>> 0) & 0xFFFFFFFF);

        buffer.putLong(entry.getDeletions());
        crc32.update((int) (entry.getDeletions() >>> 32) & 0xFFFFFFFF);
        crc32.update((int) (entry.getDeletions() >>> 0) & 0xFFFFFFFF);

        buffer.put(entry.isDeletOnlyNodes() ? (byte) 1 : (byte) 0);
        crc32.update(entry.isDeletOnlyNodes() ? new byte[] { (byte) 1 } : new byte[] { (byte) 0 });
    }
    buffer.putLong(crc32.getValue());

    if (useNIOMemoryMapping) {
        ((MappedByteBuffer) buffer).force();
    } else {
        buffer.rewind();
        channel.position(0);
        channel.write(buffer);
    }
}

From source file:com.MainFiles.Functions.java

public int createStan() {
    int x = 0;/* w  w  w . jav  a 2s  .c o m*/

    String filename = COUNT_FILE;
    File inwrite = new File(filename);

    // Get a file channel for the file
    try {
        FileChannel channel = new RandomAccessFile(inwrite, "rw").getChannel();
        // Use the file channel to create a lock on the file.
        // This method blocks until it can retrieve the lock.
        FileLock lock = channel.lock();
        //  if(!inwrite.exists()) {
        String s = "";
        try {
            int fileSize = (int) channel.size();
            //    System.out.println("int is" + fileSize);
            ByteBuffer bafa = ByteBuffer.allocate(fileSize);
            int numRead = 0;
            while (numRead >= 0) {
                numRead = channel.read(bafa);
                bafa.rewind();
                for (int i = 0; i < numRead; i++) {
                    int b = (int) bafa.get();
                    char c = (char) b;
                    s = s + c;
                }
            }

            x = Integer.parseInt(s);
            if (x > 999999) {
                x = 100000;
            } else if (x < 100000) {
                x = 100000;
            }
            x = ++x;
            String xx = String.valueOf(x);
            byte[] yy = xx.getBytes();
            channel.truncate(0);
            channel.write(ByteBuffer.wrap(yy));
            // channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        lock.release();
        // Close the file
        channel.close();
    } catch (FileNotFoundException e) {
        String message = "The file " + inwrite.getName() + " does not exist. So no input can be written on it";
        System.out.println(message);
        e.printStackTrace();
        //log to error file
    } catch (IOException e) {
        System.out.println("Problem writing to the logfile " + inwrite.getName());

    }

    filename = "";
    return x;
}