Java Code Examples for java.io.RandomAccessFile.setLength()

The following are Jave code examples for showing how to use setLength() of the java.io.RandomAccessFile class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: flume-release-1.7.0   File: TestFileChannelRestart.java   Source Code and License Vote up 6 votes
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();
  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);
}
 
Example 2
Project: IO   File: EWFOutput.java   Source Code and License Vote up 6 votes
/**
 * Creates a new EWFOutput with the given parameters.
 * @param toImage The device this image is of.
 * @param chunkQueue The source of data chunks to build the {@link SectorsSection Sectors} segments with.
 * @param outputFile The file to write the output to. Should end in .E01.
 * @param md5Hash The source of the MD5 digest hash.
 * @param sha1Hash The source of the SHA1 digest hash.
 * @param options The options used for this image.
 * @throws IOException
 */
public EWFOutput(Device toImage, BlockingQueue<Future<DataChunk>> chunkQueue, File outputFile,
        FutureTask<byte[]> md5Hash, FutureTask<byte[]> sha1Hash, AdvancedOptions options) throws IOException {
    super("EWFWriter");
    this.fileNumber = 1;
    this.outputFile = outputFile;
    this.expectedSize = toImage.getSize();
    this.serialNumber = toImage.getSerialNumber();
    this.volumeManager = new VolumeSectionManager(toImage);
    if (!outputFile.exists()) {
        if (this.outputFile.getParentFile() != null) {
            this.outputFile.getParentFile().mkdirs();
        }
        this.outputFile.createNewFile();
    }
    this.md5HashSource = md5Hash;
    this.sha1HashSource = sha1Hash;
    currentOutputFile = new RandomAccessFile(this.outputFile.getAbsolutePath(), "rw");
    currentOutputFile.setLength(0);
    this.chunkQueue = chunkQueue;
    this.sectorSize = 512; // TODO: remove hardcoded
    this.options = options;
    this.startTime = LocalDateTime.now();
}
 
Example 3
Project: https-github.com-apache-zookeeper   File: FileTxnLog.java   Source Code and License Vote up 6 votes
/**
 * truncate the current transaction logs
 * @param zxid the zxid to truncate the logs to
 * @return true if successful false if not
 */
public boolean truncate(long zxid) throws IOException {
    FileTxnIterator itr = null;
    try {
        itr = new FileTxnIterator(this.logDir, zxid);
        PositionInputStream input = itr.inputStream;
        if(input == null) {
            throw new IOException("No log files found to truncate! This could " +
                    "happen if you still have snapshots from an old setup or " +
                    "log files were deleted accidentally or dataLogDir was changed in zoo.cfg.");
        }
        long pos = input.getPosition();
        // now, truncate at the current position
        RandomAccessFile raf=new RandomAccessFile(itr.logFile,"rw");
        raf.setLength(pos);
        raf.close();
        while(itr.goToNextLog()) {
            if (!itr.logFile.delete()) {
                LOG.warn("Unable to truncate {}", itr.logFile);
            }
        }
    } finally {
        close(itr);
    }
    return true;
}
 
Example 4
Project: https-github.com-apache-zookeeper   File: InvalidSnapshotTest.java   Source Code and License Vote up 5 votes
/**
 * Validate that the server can come up on an invalid snapshot - by
 * reverting to a prior snapshot + associated logs.
 */
@Test
public void testInvalidSnapshot() throws Exception {
    ZooKeeper zk = createClient();
    try {
        for (int i = 0; i < 2000; i++) {
            zk.create("/invalidsnap-" + i, new byte[0],
                    Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
    } finally {
        zk.close();
    }
    NIOServerCnxnFactory factory = (NIOServerCnxnFactory)serverFactory;
    stopServer();

    // now corrupt the snapshot
    File snapFile = factory.zkServer.getTxnLogFactory().findMostRecentSnapshot();
    LOG.info("Corrupting " + snapFile);
    RandomAccessFile raf = new RandomAccessFile(snapFile, "rws");
    raf.setLength(3);
    raf.close();

    // now restart the server
    startServer();

    // verify that the expected data exists and wasn't lost
    zk = createClient();
    try {
        assertTrue("the node should exist",
                (zk.exists("/invalidsnap-1999", false) != null));
    } finally {
        zk.close();
    }
}
 
Example 5
Project: javaportfolio   File: Tail.java   Source Code and License Vote up 5 votes
public static void removeLastLine(String filename, int len) {
	 try{
            RandomAccessFile raf = new RandomAccessFile(filename, "rw");
            long length = raf.length();
           
            raf.setLength(length - len);
           
            raf.close();
            }
	 	
	 		catch(Exception ex){
            ex.printStackTrace();
            }
}
 
Example 6
Project: GitHub   File: Relay.java   Source Code and License Vote up 5 votes
/**
 * Creates a new relay that reads a live stream from {@code upstream}, using {@code file} to share
 * that data with other sources.
 *
 * <p><strong>Warning:</strong> callers to this method must immediately call {@link #newSource} to
 * create a source and close that when they're done. Otherwise a handle to {@code file} will be
 * leaked.
 */
public static Relay edit(
    File file, Source upstream, ByteString metadata, long bufferMaxSize) throws IOException {
  RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
  Relay result = new Relay(randomAccessFile, upstream, 0L, metadata, bufferMaxSize);

  // Write a dirty header. That way if we crash we won't attempt to recover this.
  randomAccessFile.setLength(0L);
  result.writeHeader(PREFIX_DIRTY, -1L, -1L);

  return result;
}
 
Example 7
Project: Tarski   File: Util.java   Source Code and License Vote up 5 votes
/** Copy file.content[from...f.length-1] into file.content[to...], then truncate the file after that point.
 * <p> If (from &gt; to), this means we simply delete the portion of the file beginning at "to" and up to but excluding "from".
 * <p> If (from &lt; to), this means we insert (to-from) number of ARBITRARY bytes into the "from" location
 *     and shift the original file content accordingly.
 * <p> Note: after this operation, the file's current position will be moved to the start of the file.
 * @throws IOException if (from &lt; 0) || (to &lt; 0) || (from &gt;= file.length())
 */
public static void shift (RandomAccessFile file, long from, long to) throws IOException {
   long total = file.length();
   if (from<0 || from>=total || to<0) throw new IOException(); else if (from==to) {file.seek(0); return;}
   final byte buf[] = new byte[4096];
   int res;
   if (from>to) {
      while(true) {
         file.seek(from);
         if ((res=file.read(buf)) <= 0) { file.setLength(to); file.seek(0); return; }
         file.seek(to); file.write(buf, 0, res); from=from+res; to=to+res;
      }
   } else {
      file.seek(total);
      for(long todo=to-from; todo>0;) {
         if (todo >= buf.length) {file.write(buf); todo = todo - buf.length;} else {file.write(buf, 0, (int)todo); break;}
      }
      for(long todo=total-from; todo>0; total=total-res, todo=todo-res) {
         if (todo > buf.length) res=buf.length; else res=(int)todo;
         file.seek(total - res);
         for(int done=0; done<res;) { int r=file.read(buf, done, res-done); if (r<=0) throw new IOException(); else done += r; }
         file.seek(total - res + (to - from));
         file.write(buf, 0, res);
      }
   }
   file.seek(0);
}
 
Example 8
Project: Hubs   File: JseIoLib.java   Source Code and License Vote up 5 votes
protected File openFile( String filename, boolean readMode, boolean appendMode, boolean updateMode, boolean binaryMode ) throws IOException {
	RandomAccessFile f = new RandomAccessFile(filename,readMode? "r": "rw");
	if ( appendMode ) {
		f.seek(f.length());
	} else {
		if ( ! readMode )
			f.setLength(0);
	}
	return new FileImpl( f );
}
 
Example 9
Project: ultrasonic   File: DownloadFile.java   Source Code and License Vote up 5 votes
private static void updateModificationDate(File file)
{
	if (file.exists())
	{
		boolean ok = file.setLastModified(System.currentTimeMillis());

		if (!ok)
		{
			Log.i(TAG, String.format("Failed to set last-modified date on %s, trying alternate method", file));

			try
			{
				// Try alternate method to update last modified date to current time
				// 	Found at https://code.google.com/p/android/issues/detail?id=18624
				RandomAccessFile raf = new RandomAccessFile(file, "rw");
				long length = raf.length();
				raf.setLength(length + 1);
				raf.setLength(length);
				raf.close();
			}
			catch (Exception e)
			{
				Log.w(TAG, String.format("Failed to set last-modified date on %s", file));
			}
		}
	}
}
 
Example 10
Project: sstore-soft   File: JavaSystem.java   Source Code and License Vote up 5 votes
public static void setRAFileLength(RandomAccessFile raFile,
                                       long length) throws IOException {

//#ifdef JAVA2FULL
        raFile.setLength(length);

//#endif
    }
 
Example 11
Project: LuaViewPlayground   File: JseIoLib.java   Source Code and License Vote up 5 votes
protected File openFile(String filename, boolean readMode, boolean appendMode, boolean updateMode, boolean binaryMode) throws IOException {
    RandomAccessFile f = new RandomAccessFile(filename, readMode ? "r" : "rw");
    if (appendMode) {
        f.seek(f.length());
    } else {
        if (!readMode)
            f.setLength(0);
    }
    return new FileImpl(f);
}
 
Example 12
Project: parabuild-ci   File: JavaSystem.java   Source Code and License Vote up 5 votes
public static void setRAFileLength(RandomAccessFile raFile,
                                       long length) throws IOException {

//#ifdef JAVA2FULL
        raFile.setLength(length);

//#endif
    }
 
Example 13
Project: Tarski   File: Util.java   Source Code and License Vote up 5 votes
/** Copy file.content[from...f.length-1] into file.content[to...], then truncate the file after that point.
 * <p> If (from &gt; to), this means we simply delete the portion of the file beginning at "to" and up to but excluding "from".
 * <p> If (from &lt; to), this means we insert (to-from) number of ARBITRARY bytes into the "from" location
 *     and shift the original file content accordingly.
 * <p> Note: after this operation, the file's current position will be moved to the start of the file.
 * @throws IOException if (from &lt; 0) || (to &lt; 0) || (from &gt;= file.length())
 */
public static void shift (RandomAccessFile file, long from, long to) throws IOException {
   long total = file.length();
   if (from<0 || from>=total || to<0) throw new IOException(); else if (from==to) {file.seek(0); return;}
   final byte buf[] = new byte[4096];
   int res;
   if (from>to) {
      while(true) {
         file.seek(from);
         if ((res=file.read(buf)) <= 0) { file.setLength(to); file.seek(0); return; }
         file.seek(to); file.write(buf, 0, res); from=from+res; to=to+res;
      }
   } else {
      file.seek(total);
      for(long todo=to-from; todo>0;) {
         if (todo >= buf.length) {file.write(buf); todo = todo - buf.length;} else {file.write(buf, 0, (int)todo); break;}
      }
      for(long todo=total-from; todo>0; total=total-res, todo=todo-res) {
         if (todo > buf.length) res=buf.length; else res=(int)todo;
         file.seek(total - res);
         for(int done=0; done<res;) { int r=file.read(buf, done, res-done); if (r<=0) throw new IOException(); else done += r; }
         file.seek(total - res + (to - from));
         file.write(buf, 0, res);
      }
   }
   file.seek(0);
}
 
Example 14
Project: hadoop   File: TestAppendSnapshotTruncate.java   Source Code and License Vote up 5 votes
private boolean truncate(long newLength, StringBuilder b) throws IOException {
  final RandomAccessFile raf = new RandomAccessFile(localFile, "rw");
  raf.setLength(newLength);
  raf.close();

  final boolean isReady = dfs.truncate(file, newLength);
  b.append(", newLength=").append(newLength)
   .append(", isReady=").append(isReady);
  if (!isReady) {
    TestFileTruncate.checkBlockRecovery(file, dfs, 100, 300L);
  }
  return isReady;
}
 
Example 15
Project: HtmlNative   File: JseIoLib.java   Source Code and License Vote up 5 votes
protected File openFile( String filename, boolean readMode, boolean appendMode, boolean updateMode, boolean binaryMode ) throws IOException {
	RandomAccessFile f = new RandomAccessFile(filename,readMode? "r": "rw");
	if ( appendMode ) {
		f.seek(f.length());
	} else {
		if ( ! readMode )
			f.setLength(0);
	}
	return new FileImpl( f );
}
 
Example 16
Project: LCL   File: AsyncDownload.java   Source Code and License Vote up 5 votes
public List<DownloadThread> download() throws Exception {
    callback.log("開始下載 " + path);
    callback.log("存储至 " + targetFilePath);
    URL url = new URL(path);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(10000);

    int code = connection.getResponseCode();
    if (code == 200) {
        long connectionLength = connection.getContentLengthLong();
        length = connectionLength;
        map.put("length", connection.getContentLengthLong());
        callback.log("文件大小: " + getSize(connection.getContentLengthLong()));
        RandomAccessFile randomAccessFile = new RandomAccessFile(new File(targetFilePath, getFileName(url)), "rw");
        randomAccessFile.setLength(connectionLength);
        long blockSize = connectionLength / threadCount;
        for (int threadId = 0; threadId < threadCount; threadId++) {
            long startIndex = threadId * blockSize;
            long endIndex = (threadId + 1) * blockSize - 1;
            if (threadId == (threadCount - 1)) {
                endIndex = connectionLength - 1;
            }
            DownloadThread dl = new DownloadThread(threadId, startIndex, endIndex, callback);
            dl.start();
            threads.add(dl);
        }
        List<Thread> list = new ArrayList<>(threads);
        list.add(Thread.currentThread());
        tasks.add(list);
        randomAccessFile.close();
    }
    return threads;
}
 
Example 17
Project: org.alloytools.alloy   File: SimpleCLI.java   Source Code and License Vote up 4 votes
public SimpleReporter() throws IOException {
	os = new RandomAccessFile(".alloy.tmp", "rw");
	os.setLength(0);
}
 
Example 18
Project: org.alloytools.alloy   File: Util.java   Source Code and License Vote up 4 votes
/**
 * Copy file.content[from...f.length-1] into file.content[to...], then
 * truncate the file after that point.
 * <p>
 * If (from &gt; to), this means we simply delete the portion of the file
 * beginning at "to" and up to but excluding "from".
 * <p>
 * If (from &lt; to), this means we insert (to-from) number of ARBITRARY
 * bytes into the "from" location and shift the original file content
 * accordingly.
 * <p>
 * Note: after this operation, the file's current position will be moved to
 * the start of the file.
 * 
 * @throws IOException if (from &lt; 0) || (to &lt; 0) || (from &gt;=
 *             file.length())
 */
public static void shift(RandomAccessFile file, long from, long to) throws IOException {
	long total = file.length();
	if (from < 0 || from >= total || to < 0)
		throw new IOException();
	else if (from == to) {
		file.seek(0);
		return;
	}
	final byte buf[] = new byte[4096];
	int res;
	if (from > to) {
		while (true) {
			file.seek(from);
			if ((res = file.read(buf)) <= 0) {
				file.setLength(to);
				file.seek(0);
				return;
			}
			file.seek(to);
			file.write(buf, 0, res);
			from = from + res;
			to = to + res;
		}
	} else {
		file.seek(total);
		for (long todo = to - from; todo > 0;) {
			if (todo >= buf.length) {
				file.write(buf);
				todo = todo - buf.length;
			} else {
				file.write(buf, 0, (int) todo);
				break;
			}
		}
		for (long todo = total - from; todo > 0; total = total - res, todo = todo - res) {
			if (todo > buf.length)
				res = buf.length;
			else
				res = (int) todo;
			file.seek(total - res);
			for (int done = 0; done < res;) {
				int r = file.read(buf, done, res - done);
				if (r <= 0)
					throw new IOException();
				else
					done += r;
			}
			file.seek(total - res + (to - from));
			file.write(buf, 0, res);
		}
	}
	file.seek(0);
}
 
Example 19
Project: wechat-mall   File: LocalPageCacheUtil.java   Source Code and License Vote up 4 votes
private static void init(File abort) throws FileNotFoundException, IOException {
    raf = new RandomAccessFile(abort, "rw");
    raf.setLength(FILE_SIZE);
    channel = raf.getChannel();
    buff = channel.map(FileChannel.MapMode.READ_WRITE, 0, FILE_SIZE);
}
 
Example 20
Project: Hydrograph   File: PreStartActivity.java   Source Code and License Vote up 4 votes
private void updateData(byte[] text, String javaHome, String end,RandomAccessFile file) throws IOException {
	String data=new String(text);
	data=StringUtils.replace(data, end, javaHome);
	file.setLength(data.length());
	file.writeBytes(data);
}