当前位置: 首页>>代码示例>>Java>>正文


Java RandomAccessFile.setLength方法代码示例

本文整理汇总了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);
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:26,代码来源:TestFileChannelRestart.java

示例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();
}
 
开发者ID:ciphertechsolutions,项目名称:IO,代码行数:34,代码来源:EWFOutput.java

示例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;
}
 
开发者ID:didichuxing2,项目名称:https-github.com-apache-zookeeper,代码行数:31,代码来源:FileTxnLog.java

示例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();
    }
}
 
开发者ID:didichuxing2,项目名称:https-github.com-apache-zookeeper,代码行数:38,代码来源:InvalidSnapshotTest.java

示例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();
            }
}
 
开发者ID:skarna1,项目名称:javaportfolio,代码行数:15,代码来源:Tail.java

示例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;
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:20,代码来源:Relay.java

示例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 &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);
}
 
开发者ID:ModelWriter,项目名称:Tarski,代码行数:34,代码来源:Util.java

示例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 );
}
 
开发者ID:nekocode,项目名称:Hubs,代码行数:11,代码来源:JseIoLib.java

示例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));
			}
		}
	}
}
 
开发者ID:ultrasonic,项目名称:ultrasonic,代码行数:28,代码来源:DownloadFile.java

示例10: setRAFileLength

import java.io.RandomAccessFile; //导入方法依赖的package包/类
public static void setRAFileLength(RandomAccessFile raFile,
                                       long length) throws IOException {

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

//#endif
    }
 
开发者ID:s-store,项目名称:sstore-soft,代码行数:9,代码来源:JavaSystem.java

示例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);
}
 
开发者ID:alibaba,项目名称:LuaViewPlayground,代码行数:11,代码来源:JseIoLib.java

示例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;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:14,代码来源:TestAppendSnapshotTruncate.java

示例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;
}
 
开发者ID:IzzelAliz,项目名称:LCL,代码行数:36,代码来源:AsyncDownload.java

示例14: SimpleReporter

import java.io.RandomAccessFile; //导入方法依赖的package包/类
public SimpleReporter() throws IOException {
	os = new RandomAccessFile(".alloy.tmp", "rw");
	os.setLength(0);
}
 
开发者ID:AlloyTools,项目名称:org.alloytools.alloy,代码行数:5,代码来源:SimpleCLI.java

示例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 &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);
}
 
开发者ID:AlloyTools,项目名称:org.alloytools.alloy,代码行数:71,代码来源:Util.java


注:本文中的java.io.RandomAccessFile.setLength方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。