本文整理汇总了Java中java.io.RandomAccessFile.setLength方法的典型用法代码示例。如果您正苦于以下问题:Java RandomAccessFile.setLength方法的具体用法?Java RandomAccessFile.setLength怎么用?Java RandomAccessFile.setLength使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.io.RandomAccessFile
的用法示例。
在下文中一共展示了RandomAccessFile.setLength方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doTestTruncatedCheckpointMeta
import java.io.RandomAccessFile; //导入方法依赖的package包/类
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);
}
示例2: EWFOutput
import java.io.RandomAccessFile; //导入方法依赖的package包/类
/**
* 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();
}
示例3: truncate
import java.io.RandomAccessFile; //导入方法依赖的package包/类
/**
* 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;
}
示例4: testInvalidSnapshot
import java.io.RandomAccessFile; //导入方法依赖的package包/类
/**
* 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();
}
}
示例5: removeLastLine
import java.io.RandomAccessFile; //导入方法依赖的package包/类
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();
}
}
示例6: edit
import java.io.RandomAccessFile; //导入方法依赖的package包/类
/**
* 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;
}
示例7: shift
import java.io.RandomAccessFile; //导入方法依赖的package包/类
/** Copy file.content[from...f.length-1] into file.content[to...], then truncate the file after that point.
* <p> If (from > to), this means we simply delete the portion of the file beginning at "to" and up to but excluding "from".
* <p> If (from < 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 < 0) || (to < 0) || (from >= 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);
}
示例8: openFile
import java.io.RandomAccessFile; //导入方法依赖的package包/类
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 );
}
示例9: updateModificationDate
import java.io.RandomAccessFile; //导入方法依赖的package包/类
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));
}
}
}
}
示例10: setRAFileLength
import java.io.RandomAccessFile; //导入方法依赖的package包/类
public static void setRAFileLength(RandomAccessFile raFile,
long length) throws IOException {
//#ifdef JAVA2FULL
raFile.setLength(length);
//#endif
}
示例11: openFile
import java.io.RandomAccessFile; //导入方法依赖的package包/类
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);
}
示例12: truncate
import java.io.RandomAccessFile; //导入方法依赖的package包/类
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;
}
示例13: download
import java.io.RandomAccessFile; //导入方法依赖的package包/类
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;
}
示例14: SimpleReporter
import java.io.RandomAccessFile; //导入方法依赖的package包/类
public SimpleReporter() throws IOException {
os = new RandomAccessFile(".alloy.tmp", "rw");
os.setLength(0);
}
示例15: shift
import java.io.RandomAccessFile; //导入方法依赖的package包/类
/**
* Copy file.content[from...f.length-1] into file.content[to...], then
* truncate the file after that point.
* <p>
* If (from > to), this means we simply delete the portion of the file
* beginning at "to" and up to but excluding "from".
* <p>
* If (from < 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 < 0) || (to < 0) || (from >=
* 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);
}