Java Code Examples for java.nio.channels.FileChannel#truncate()

The following examples show how to use java.nio.channels.FileChannel#truncate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileChannelUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenTruncateFile_thenCorrect() throws IOException {
    String input = "this is a test input";

    FileOutputStream fout = new FileOutputStream("src/test/resources/test_truncate.txt");
    FileChannel channel = fout.getChannel();

    ByteBuffer buff = ByteBuffer.wrap(input.getBytes());
    channel.write(buff);
    buff.flip();

    channel = channel.truncate(5);
    assertEquals(5, channel.size());

    fout.close();
    channel.close();
}
 
Example 2
Source File: LocalFilesystem.java    From keemob with MIT License 6 votes vote down vote up
@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.");
       }

       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();
       }


}
 
Example 3
Source File: BufferReaderWriterUtilTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void readPrematureEndOfFile1() throws Exception {
	final FileChannel fc = tmpFileChannel();
	final Buffer buffer = createTestBuffer();
	final MemorySegment readBuffer = MemorySegmentFactory.allocateUnpooledOffHeapMemory(buffer.getSize(), null);

	BufferReaderWriterUtil.writeToByteChannel(fc, buffer, BufferReaderWriterUtil.allocatedWriteBufferArray());
	fc.truncate(fc.position() - 1);
	fc.position(0);

	try {
		BufferReaderWriterUtil.readFromByteChannel(
				fc, BufferReaderWriterUtil.allocatedHeaderBuffer(), readBuffer, FreeingBufferRecycler.INSTANCE);
		fail();
	}
	catch (IOException e) {
		// expected
	}
}
 
Example 4
Source File: LocalFilesystem.java    From keemob with MIT License 6 votes vote down vote up
@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.");
       }

       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();
       }


}
 
Example 5
Source File: FileUtils.java    From cordova-android-chromeview with Apache License 2.0 6 votes vote down vote up
/**
 * Truncate the file to size
 *
 * @param filename
 * @param size
 * @throws FileNotFoundException, IOException
 * @throws NoModificationAllowedException
 */
private long truncateFile(String filename, long size) throws FileNotFoundException, IOException, NoModificationAllowedException {
    if (filename.startsWith("content://")) {
        throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
    }

    filename = FileHelper.getRealPath(filename, cordova);

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

        return raf.length();
    } finally {
        raf.close();
    }
}
 
Example 6
Source File: BufferReaderWriterUtilTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void readPrematureEndOfFile2() throws Exception {
	final FileChannel fc = tmpFileChannel();
	final Buffer buffer = createTestBuffer();
	final MemorySegment readBuffer = MemorySegmentFactory.allocateUnpooledOffHeapMemory(buffer.getSize(), null);

	BufferReaderWriterUtil.writeToByteChannel(fc, buffer, BufferReaderWriterUtil.allocatedWriteBufferArray());
	fc.truncate(2); // less than a header size
	fc.position(0);

	try {
		BufferReaderWriterUtil.readFromByteChannel(
				fc, BufferReaderWriterUtil.allocatedHeaderBuffer(), readBuffer, FreeingBufferRecycler.INSTANCE);
		fail();
	}
	catch (IOException e) {
		// expected
	}
}
 
Example 7
Source File: BufferReaderWriterUtilTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void readPrematureEndOfFile2() throws Exception {
	final FileChannel fc = tmpFileChannel();
	final Buffer buffer = createTestBuffer();
	final MemorySegment readBuffer = MemorySegmentFactory.allocateUnpooledOffHeapMemory(buffer.getSize(), null);

	BufferReaderWriterUtil.writeToByteChannel(fc, buffer, BufferReaderWriterUtil.allocatedWriteBufferArray());
	fc.truncate(2); // less than a header size
	fc.position(0);

	try {
		BufferReaderWriterUtil.readFromByteChannel(
				fc, BufferReaderWriterUtil.allocatedHeaderBuffer(), readBuffer, FreeingBufferRecycler.INSTANCE);
		fail();
	}
	catch (IOException e) {
		// expected
	}
}
 
Example 8
Source File: LocalFilesystem.java    From L.TileLayer.Cordova with MIT License 6 votes vote down vote up
@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.URL + " does not exist.");
       }
       
       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();
       }


}
 
Example 9
Source File: DatabaseImpl.java    From jackcess with Apache License 2.0 5 votes vote down vote up
/**
 * 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_
 */
public static DatabaseImpl create(FileFormat fileFormat, Path 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 for " + mdbFile);
  }
  if(details.getEmptyFilePath() == null) {
    throw new IOException("File format " + fileFormat +
                          " does not support file creation for " + mdbFile);
  }

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

  boolean success = false;
  try {
    channel.truncate(0);
    transferDbFrom(channel, getResourceAsStream(details.getEmptyFilePath()));
    channel.force(true);
    DatabaseImpl db = new DatabaseImpl(mdbFile, channel, closeChannel, autoSync,
                                       fileFormat, charset, timeZone, null,
                                       false);
    success = true;
    return db;
  } finally {
    if(!success && closeChannel) {
      // something blew up, shutdown the channel (quietly)
      ByteUtil.closeQuietly(channel);
    }
  }
}
 
Example 10
Source File: RawSamples.java    From Android-Audio-Recorder with Apache License 2.0 5 votes vote down vote up
public void trunk(long pos) {
    try {
        FileChannel outChan = new FileOutputStream(in, true).getChannel();
        outChan.truncate(getBufferLen(pos));
        outChan.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Source File: JsonRequestMessageTest.java    From conga with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpOnce() {
  new File("target/test").mkdirs();
  
  try {
    FileChannel channel = FileChannel.open(path, StandardOpenOption.APPEND);
    channel.truncate(0);
    channel.close();
  } catch (IOException e) {

  }
}
 
Example 12
Source File: RecoverMergeTask.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
private void truncateFiles() throws IOException {
  logger.info("{} truncating {} files", taskName, analyzer.getFileLastPositions().size());
  for (Entry<File, Long> entry : analyzer.getFileLastPositions().entrySet()) {
    File file = entry.getKey();
    Long lastPosition = entry.getValue();
    if (file.exists() && file.length() != lastPosition) {
      try (FileInputStream fileInputStream = new FileInputStream(file)) {
        FileChannel channel = fileInputStream.getChannel();
        channel.truncate(lastPosition);
        channel.close();
      }
    }
  }
  analyzer.setFileLastPositions(null);
}
 
Example 13
Source File: FileHandlerTests.java    From slf4android with MIT License 5 votes vote down vote up
private String readAndClearFileEntries() throws IOException {
    handler.flush();
    String currentFileName = handler.getCurrentFileName();
    String contents = Files.contentOf(new File(currentFileName), Charset.forName("UTF-8"));
    FileChannel outChan = new FileOutputStream(currentFileName, true).getChannel();
    outChan.truncate(0);
    outChan.close();
    return contents;
}
 
Example 14
Source File: AppendTmxWriter.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
private void truncateFile() {
	FileChannel channel = out.getChannel();
	try {
		channel.truncate(offset);
	} catch (IOException e) {
		LOGGER.error("R:truncate file failed", e);
	}
}
 
Example 15
Source File: DataConsistentFileOutputStream.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static void truncateFileToConsistentSize(FileOutputStream fos, long size) {
    try {
        FileChannel fch = fos.getChannel();
        fch.truncate(size);
        fch.force(true);
    } catch (IOException ex) {
        Logger.getLogger(DataConsistentFileOutputStream.class.getName()).log(
                Level.INFO,
                "Not able to truncate file to the data consistent size of "+size+" bytes.",
                ex);
    }
}
 
Example 16
Source File: TestOfflineEditsViewer.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecoveryMode() throws IOException {
  // edits generated by nnHelper (MiniDFSCluster), should have all op codes
  // binary, XML, reparsed binary
  String edits = nnHelper.generateEdits();
  FileOutputStream os = new FileOutputStream(edits, true);
  // Corrupt the file by truncating the end
  FileChannel editsFile = os.getChannel();
  editsFile.truncate(editsFile.size() - 5);

  String editsParsedXml = folder.newFile("editsRecoveredParsed.xml")
      .getAbsolutePath();
  String editsReparsed = folder.newFile("editsRecoveredReparsed")
      .getAbsolutePath();
  String editsParsedXml2 = folder.newFile("editsRecoveredParsed2.xml")
      .getAbsolutePath();

  // Can't read the corrupted file without recovery mode
  assertEquals(-1, runOev(edits, editsParsedXml, "xml", false));

  // parse to XML then back to binary
  assertEquals(0, runOev(edits, editsParsedXml, "xml", true));
  assertEquals(0, runOev(editsParsedXml, editsReparsed, "binary", false));
  assertEquals(0, runOev(editsReparsed, editsParsedXml2, "xml", false));

  // judgment time
  assertTrue("Test round trip", FileUtils.contentEqualsIgnoreEOL(
      new File(editsParsedXml), new File(editsParsedXml2), "UTF-8"));

  os.close();
}
 
Example 17
Source File: ResultsLog.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void truncate() throws IOException {
    if ( isOpen.get() ) {
        throw new IOException( "Cannot truncate while log is open for writing. Close the log then truncate." );
    }

    // Synchronize on isOpen to prevent re-opening while truncating (rare)
    synchronized ( isOpen ) {
        File results = new File( resultsFile.get() );
        FileChannel channel = new FileOutputStream( results, true ).getChannel();
        channel.truncate( 0 );
        channel.close();
        resultCount.set( 0 );
    }
}
 
Example 18
Source File: Transfer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void xferTest03() throws Exception { // for bug 4559072
    byte[] srcData = new byte[] {1,2,3,4} ;

    // get filechannel for the source file.
    File source = File.createTempFile("source", null);
    source.deleteOnExit();
    RandomAccessFile raf1 = new RandomAccessFile(source, "rw");
    FileChannel fc1 = raf1.getChannel();
    fc1.truncate(0);

    // write out data to the file channel
    int bytesWritten = 0;
    while (bytesWritten < 4) {
        bytesWritten = fc1.write(ByteBuffer.wrap(srcData));
    }

    // get filechannel for the dst file.
    File dest = File.createTempFile("dest", null);
    dest.deleteOnExit();
    RandomAccessFile raf2 = new RandomAccessFile(dest, "rw");
    FileChannel fc2 = raf2.getChannel();
    fc2.truncate(0);

    fc1.transferTo(0, srcData.length + 1, fc2);

    if (fc2.size() > 4)
        throw new Exception("xferTest03 failed");

    fc1.close();
    fc2.close();
    raf1.close();
    raf2.close();

    source.delete();
    dest.delete();
}
 
Example 19
Source File: TestOfflineEditsViewer.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecoveryMode() throws IOException {
  // edits generated by nnHelper (MiniDFSCluster), should have all op codes
  // binary, XML, reparsed binary
  String edits = nnHelper.generateEdits();
  FileOutputStream os = new FileOutputStream(edits, true);
  // Corrupt the file by truncating the end
  FileChannel editsFile = os.getChannel();
  editsFile.truncate(editsFile.size() - 5);

  String editsParsedXml = folder.newFile("editsRecoveredParsed.xml")
      .getAbsolutePath();
  String editsReparsed = folder.newFile("editsRecoveredReparsed")
      .getAbsolutePath();
  String editsParsedXml2 = folder.newFile("editsRecoveredParsed2.xml")
      .getAbsolutePath();

  // Can't read the corrupted file without recovery mode
  assertEquals(-1, runOev(edits, editsParsedXml, "xml", false));

  // parse to XML then back to binary
  assertEquals(0, runOev(edits, editsParsedXml, "xml", true));
  assertEquals(0, runOev(editsParsedXml, editsReparsed, "binary", false));
  assertEquals(0, runOev(editsReparsed, editsParsedXml2, "xml", false));

  // judgment time
  assertTrue("Test round trip", FileUtils.contentEqualsIgnoreEOL(
      new File(editsParsedXml), new File(editsParsedXml2), "UTF-8"));

  os.close();
}
 
Example 20
Source File: LocalFileSystemOperations.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "resource" )
@Override
public void copyFile(
        String sourceFile,
        String destinationFile,
        boolean failOnError ) {

    File inputFile = new File(sourceFile);
    checkFileExistence(inputFile);

    FileChannel srcChannel = null;
    FileChannel dstChannel = null;

    try {
        // Create channel on the source
        srcChannel = new FileInputStream(sourceFile).getChannel();

        // Create channel on the destination
        dstChannel = new FileOutputStream(destinationFile).getChannel();

        // Copy file contents from source to destination
        dstChannel.truncate(0);

        if (log.isDebugEnabled()) {
            log.debug("Copying file '" + sourceFile + "' of " + srcChannel.size() + "bytes to '"
                      + destinationFile + "'");
        }

        /* Copy the file in chunks.
         * If we provide the whole file at once, the copy process does not start or does not
         * copy the whole file on some systems when the file is a very large one - usually
         * bigger than 2 GBs
         */
        final long CHUNK = 16 * 1024 * 1024; // 16 MB chunks
        for (long pos = 0; pos < srcChannel.size(); ) {
            pos += dstChannel.transferFrom(srcChannel, pos, CHUNK);
        }

        if (srcChannel.size() != dstChannel.size()) {
            throw new FileSystemOperationException("Size of the destination file \"" + destinationFile
                                                   + "\" and the source file \"" + sourceFile
                                                   + "\" mismatch!");
        }

        if (osType.isUnix()) {
            // set the original file permission to the new file
            setFilePermissions(destinationFile, getFilePermissions(sourceFile));
        }

    } catch (IOException e) {
        throw new FileSystemOperationException("Unable to copy file '" + sourceFile + "' to '"
                                               + destinationFile + "'", e);
    } finally {
        // Close the channels
        IoUtils.closeStream(srcChannel,
                            "Unable to close input channel while copying file '" + sourceFile + "' to '"
                            + destinationFile + "'");
        IoUtils.closeStream(dstChannel,
                            "Unable to close destination channel while copying file '" + sourceFile
                            + "' to '" + destinationFile + "'");
    }
}