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


Java RandomAccessFile类代码示例

本文整理汇总了Java中java.io.RandomAccessFile的典型用法代码示例。如果您正苦于以下问题:Java RandomAccessFile类的具体用法?Java RandomAccessFile怎么用?Java RandomAccessFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


RandomAccessFile类属于java.io包,在下文中一共展示了RandomAccessFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: initialize

import java.io.RandomAccessFile; //导入依赖的package包/类
private static void initialize(File file) throws IOException {
    File tempFile = new File(file.getPath() + ".tmp");
    RandomAccessFile raf = open(tempFile);
    try {
        raf.setLength(PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM);
        raf.seek(0);
        byte[] headerBuffer = new byte[16];
        writeInts(headerBuffer, 4096, 0, 0, 0);
        raf.write(headerBuffer);
        if (!tempFile.renameTo(file)) {
            throw new IOException("Rename failed!");
        }
    } finally {
        raf.close();
    }
}
 
开发者ID:JackChan1999,项目名称:letv,代码行数:17,代码来源:QueueFile.java

示例2: setOffsetFromFile

import java.io.RandomAccessFile; //导入依赖的package包/类
public void setOffsetFromFile(RandomAccessFile f, ByteBuffer buf) throws IOException {
    long localHdrOffset = mLocalHdrOffset;
    try {
        f.seek(localHdrOffset);
        f.readFully(buf.array());
        if (buf.getInt(0) != kLFHSignature) {
            Log.w(LOG_TAG, "didn't find signature at start of lfh");
            throw new IOException();
        }
        int nameLen = buf.getShort(kLFHNameLen) & 0xFFFF;
        int extraLen = buf.getShort(kLFHExtraLen) & 0xFFFF;
        mOffset = localHdrOffset + kLFHLen + nameLen + extraLen;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}
 
开发者ID:12d,项目名称:react-native-videoplayer,代码行数:19,代码来源:ZipResourceFile.java

示例3: transformBytes

import java.io.RandomAccessFile; //导入依赖的package包/类
/**
 * Transforms bytes from |oldData| into |newData| by applying byte-for-byte addends from
 * |patchData|. The number of bytes consumed from |oldData| and |patchData|, as well as the
 * number of bytes written to |newData|, is |diffLength|. The contents of the buffers are
 * ignored and overwritten, and no guarantee is made as to their contents when this method
 * returns. This is the core of the bsdiff patching algorithm. |buffer1.length| must equal
 * |buffer2.length|, and |buffer1| and |buffer2| must be distinct objects.
 *
 * @param diffLength the length of the BsDiff entry (how many bytes to read and apply).
 * @param patchData the input stream from the BsDiff patch containing diff bytes. This stream
 *                  must be positioned so that the first byte read is the first addend to be
 *                  applied to the first byte of data to be read from |oldData|.
 * @param oldData the old file, for the diff bytes to be applied to. This input source must be
 *                positioned so that the first byte read is the first byte of data to which the
 *                first byte of addends from |patchData| should be applied.
 * @param newData the stream to write the resulting data to.
 * @param buffer1 temporary buffer to use for data transformation; contents are ignored, may be
 *                overwritten, and are undefined when this method returns.
 * @param buffer2 temporary buffer to use for data transformation; contents are ignored, may be
 *                overwritten, and are undefined when this method returns.
 */
// Visible for testing only
static void transformBytes(
    final int diffLength,
    final InputStream patchData,
    final RandomAccessFile oldData,
    final OutputStream newData,
    final byte[] buffer1,
    final byte[] buffer2)
    throws IOException {
  int numBytesLeft = diffLength;
  while (numBytesLeft > 0) {
    final int numBytesThisRound = Math.min(numBytesLeft, buffer1.length);
    oldData.readFully(buffer1, 0, numBytesThisRound);
    readFully(patchData, buffer2, 0, numBytesThisRound);
    for (int i = 0; i < numBytesThisRound; i++) {
      buffer1[i] += buffer2[i];
    }
    newData.write(buffer1, 0, numBytesThisRound);
    numBytesLeft -= numBytesThisRound;
  }
}
 
开发者ID:lizhangqu,项目名称:CorePatch,代码行数:43,代码来源:BsPatch.java

示例4: trimEOF

import java.io.RandomAccessFile; //导入依赖的package包/类
/**
 * Trim the CPM EOF byte (0x1A) from the end of a file.
 *
 * @param filename the name of the file to trim on the local filesystem
 */
protected void trimEOF(final String filename) {
    try {
        // SetLength() requires the file be open in read-write.
        RandomAccessFile contents = new RandomAccessFile(filename, "rw");
        while (contents.length() > 0) {
            contents.seek(contents.length() - 1);
            int ch = contents.read();
            if (ch == 0x1A) {
                contents.setLength(contents.length() - 1);
            } else {
                // Found a non-EOF byte
                break;
            }
        }
    } catch (IOException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
    }
}
 
开发者ID:klamonte,项目名称:jermit,代码行数:26,代码来源:XmodemSession.java

示例5: truncate

import java.io.RandomAccessFile; //导入依赖的package包/类
@Override
public void truncate(final Long length) {
    this.length = length;
    if(temporary.exists()) {
        try {
            final RandomAccessFile file = random();
            if(length < file.length()) {
                // Truncate current
                file.setLength(length);
            }
        }
        catch(IOException e) {
            log.warn(String.format("Failure truncating file %s to %d", temporary, length));
        }
    }
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:17,代码来源:FileBuffer.java

示例6: main

import java.io.RandomAccessFile; //导入依赖的package包/类
public static void main(String[] args) throws IOException {
    RandomAccessFile aFile = new RandomAccessFile("/Users/zhenpeng/aa.txt", "rw");
    FileChannel inChannel = aFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(2);
    int bytesRead = inChannel.read(buf);
    while (bytesRead != -1) {
        buf.flip();
        while (buf.hasRemaining()) {
            System.out.print((char) buf.get());
        }
        buf.clear();
        //bytesRead = inChannel.read(buf);
        //buf.putChar('f');
        bytesRead = inChannel.read(buf);
    }
    aFile.close();
}
 
开发者ID:xy1m,项目名称:PlayGround,代码行数:18,代码来源:NIO.java

示例7: corruptBlock

import java.io.RandomAccessFile; //导入依赖的package包/类
public static boolean corruptBlock(File blockFile) throws IOException {
  if (blockFile == null || !blockFile.exists()) {
    return false;
  }
  // Corrupt replica by writing random bytes into replica
  Random random = new Random();
  RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
  FileChannel channel = raFile.getChannel();
  String badString = "BADBAD";
  int rand = random.nextInt((int)channel.size()/2);
  raFile.seek(rand);
  raFile.write(badString.getBytes());
  raFile.close();
  LOG.warn("Corrupting the block " + blockFile);
  return true;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:17,代码来源:MiniDFSCluster.java

示例8: truncateFileAtURL

import java.io.RandomAccessFile; //导入依赖的package包/类
@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();
       }


}
 
开发者ID:rodrigonsh,项目名称:alerta-fraude,代码行数:24,代码来源:LocalFilesystem.java

示例9: ScaledRAFile

import java.io.RandomAccessFile; //导入依赖的package包/类
ScaledRAFile(Database database, String name,
             boolean readonly) throws FileNotFoundException, IOException {

    this.appLog   = database.logger.appLog;
    this.readOnly = readonly;
    this.fileName = name;
    this.file     = new RandomAccessFile(name, readonly ? "r"
                                                        : "rw");

    int bufferScale = database.getProperties().getIntegerProperty(
        HsqlDatabaseProperties.hsqldb_raf_buffer_scale, 12);
    int bufferSize = 1 << bufferScale;

    buffer = new byte[bufferSize];
    ba     = new HsqlByteArrayInputStream(buffer);
}
 
开发者ID:s-store,项目名称:s-store,代码行数:17,代码来源:ScaledRAFile.java

示例10: getShareDeleteFileInputStream

import java.io.RandomAccessFile; //导入依赖的package包/类
/**
 * Create a FileInputStream that shares delete permission on the
 * file opened at a given offset, i.e. other process can delete
 * the file the FileInputStream is reading. Only Windows implementation
 * uses the native interface.
 */
public static FileInputStream getShareDeleteFileInputStream(File f, long seekOffset)
    throws IOException {
  if (!Shell.WINDOWS) {
    RandomAccessFile rf = new RandomAccessFile(f, "r");
    if (seekOffset > 0) {
      rf.seek(seekOffset);
    }
    return new FileInputStream(rf.getFD());
  } else {
    // Use Windows native interface to create a FileInputStream that
    // shares delete permission on the file opened, and set it to the
    // given offset.
    //
    FileDescriptor fd = NativeIO.Windows.createFile(
        f.getAbsolutePath(),
        NativeIO.Windows.GENERIC_READ,
        NativeIO.Windows.FILE_SHARE_READ |
            NativeIO.Windows.FILE_SHARE_WRITE |
            NativeIO.Windows.FILE_SHARE_DELETE,
        NativeIO.Windows.OPEN_EXISTING);
    if (seekOffset > 0)
      NativeIO.Windows.setFilePointer(fd, seekOffset, NativeIO.Windows.FILE_BEGIN);
    return new FileInputStream(fd);
  }
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:32,代码来源:NativeIO.java

示例11: writeTxtToFile

import java.io.RandomAccessFile; //导入依赖的package包/类
public void writeTxtToFile(String strcontent, String filePath, String fileName) {
    // �����ļ���֮���������ļ�����Ȼ�����
    makeFilePath(filePath, fileName);
 
    String strFilePath = filePath + fileName;
    // ÿ��д��ʱ��������д
    String strContent = strcontent + "\r\n";
    try {
        File file = new File(strFilePath);
        if (!file.exists()) {
            Log.d("TestFile", "Create the file:" + strFilePath);
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        RandomAccessFile raf = new RandomAccessFile(file, "rwd");
        raf.seek(file.length());
        raf.write(strContent.getBytes());
        raf.close();
 
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
开发者ID:Edward7Zhang,项目名称:oneKey2Alarm,代码行数:24,代码来源:messages.java

示例12: testPutGetCorruptEvent

import java.io.RandomAccessFile; //导入依赖的package包/类
@Test(expected = CorruptEventException.class)
public void testPutGetCorruptEvent() throws Exception {
  final LogFile.RandomReader logFileReader =
      LogFileFactory.getRandomReader(dataFile, null, true);
  final FlumeEvent eventIn = TestUtils.newPersistableEvent(2500);
  final Put put = new Put(++transactionID, WriteOrderOracle.next(), eventIn);
  ByteBuffer bytes = TransactionEventRecord.toByteBuffer(put);
  FlumeEventPointer ptr = logFileWriter.put(bytes);
  logFileWriter.commit(TransactionEventRecord.toByteBuffer(
      new Commit(transactionID, WriteOrderOracle.next())));
  logFileWriter.sync();
  final int offset = ptr.getOffset();
  RandomAccessFile writer = new RandomAccessFile(dataFile, "rw");
  writer.seek(offset + 1500);
  writer.write((byte) 45);
  writer.write((byte) 12);
  writer.getFD().sync();
  logFileReader.get(offset);

  // Should have thrown an exception by now.
  Assert.fail();
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:23,代码来源:TestLogFile.java

示例13: writeChunk

import java.io.RandomAccessFile; //导入依赖的package包/类
/**
 * Write the given chunk into the given file; Note: data.length must be at
 * least 4.
 */
private static void writeChunk(RandomAccessFile file, int[] data) throws IOException {
	int crc = (-1), len = data.length - 4;
	file.write((len >>> 24) & 255);
	file.write((len >>> 16) & 255);
	file.write((len >>> 8) & 255);
	file.write(len & 255);
	for (int i = 0; i < data.length; i++) {
		int x = data[i];
		crc = table[(crc ^ x) & 255] ^ (crc >>> 8);
		file.write(x & 255);
	}
	crc = crc ^ (-1);
	file.write((crc >>> 24) & 255);
	file.write((crc >>> 16) & 255);
	file.write((crc >>> 8) & 255);
	file.write(crc & 255);
}
 
开发者ID:AlloyTools,项目名称:org.alloytools.alloy,代码行数:22,代码来源:OurPNGWriter.java

示例14: close

import java.io.RandomAccessFile; //导入依赖的package包/类
public void close() throws IOException {
  lock.readLock().lock();
  if (isOpen) {
    lock.readLock().unlock();
    lock.writeLock().lock();
    try {
      if (isOpen) {
        for (RandomAccessFile file : fileMap.values())
        {
            file.close();
        }
        fileMap.clear();
        isOpen=false;
      }
    }
    finally
    {
        lock.writeLock().unlock();
    }
  }
  else {
    lock.readLock().unlock();
  }
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:25,代码来源:FSDirectory.java

示例15: LockExclusive

import java.io.RandomAccessFile; //导入依赖的package包/类
public boolean LockExclusive(File targetFile) {

            if (targetFile == null) {
                return false;
            }
            try {
                File lockFile = new File(targetFile.getParentFile().getAbsolutePath().concat("/lock"));
                if (!lockFile.exists()) {
                    lockFile.createNewFile();
                }
                RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile.getAbsolutePath(), "rw");
                FileChannel channel = randomAccessFile.getChannel();
                java.nio.channels.FileLock lock = channel.lock();
                if (!lock.isValid()) {
                    return false;
                }
                RefCntInc(lockFile.getAbsolutePath(), lock, randomAccessFile, channel);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
 
开发者ID:7763sea,项目名称:VirtualHook,代码行数:23,代码来源:FileUtils.java


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