java.io.RandomAccessFile.setLength()方法的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(9.3k)|赞(0)|评价(0)|浏览(261)

本文整理了Java中java.io.RandomAccessFile.setLength方法的一些代码示例,展示了RandomAccessFile.setLength的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。RandomAccessFile.setLength方法的具体详情如下:
包路径:java.io.RandomAccessFile
类名称:RandomAccessFile
方法名:setLength

RandomAccessFile.setLength介绍

[英]Sets the length of this file to newLength. If the current file is smaller, it is expanded but the contents from the previous end of the file to the new end are undefined. The file is truncated if its current size is bigger than newLength. If the current file pointer position is in the truncated part, it is set to the end of the file.
[中]将此文件的长度设置为newLength。如果当前文件较小,则会展开该文件,但从文件的前一端到新一端的内容未定义。如果文件的当前大小大于newLength,则该文件将被截断。如果当前文件指针位置位于截断部分,则将其设置为文件的结尾。

代码示例

代码示例来源:origin: stackoverflow.com

import java.io.*;

class Test {
   public static void main(String args[]) throws Exception {
      RandomAccessFile f = new RandomAccessFile("t", "rw");
      f.setLength(1024 * 1024 * 1024);
   }
}

代码示例来源:origin: apache/geode

public void preBlow(String path, long maxSize, boolean preAllocate) throws IOException {
 RandomAccessFile raf = new RandomAccessFile(path, "rw");
 try {
  raf.setLength(maxSize);
 } finally {
  raf.close();
 }
}

代码示例来源:origin: apache/flink

public void open(File outputFile) throws IOException {
  outputFile.mkdirs();
  if (outputFile.exists()) {
    outputFile.delete();
  }
  outputFile.createNewFile();
  outputRAF = new RandomAccessFile(outputFile, "rw");
  outputRAF.setLength(mappedFileSizeBytes);
  outputRAF.seek(mappedFileSizeBytes - 1);
  outputRAF.writeByte(0);
  outputRAF.seek(0);
  outputChannel = outputRAF.getChannel();
  fileBuffer = outputChannel.map(FileChannel.MapMode.READ_WRITE, 0, mappedFileSizeBytes);
}

代码示例来源:origin: stackoverflow.com

RandomAccessFile f = new RandomAccessFile(fileName, "rw");
long length = f.length() - 1;
do {                     
 length -= 1;
 f.seek(length);
 byte b = f.readByte();
} while(b != 10);
f.setLength(length+1);
f.close();

代码示例来源:origin: atomix/atomix

FileBytes(File file, String mode, int size) {
 if (file == null) {
  throw new NullPointerException("file cannot be null");
 }
 if (mode == null) {
  mode = DEFAULT_MODE;
 }
 if (size < 0) {
  throw new IllegalArgumentException("size must be positive");
 }
 this.file = file;
 this.mode = mode;
 this.size = size;
 try {
  this.randomAccessFile = new RandomAccessFile(file, mode);
  if (size > randomAccessFile.length()) {
   randomAccessFile.setLength(size);
  }
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: apache/geode

private void preblow() {
 this.dirHolder.incrementTotalOplogSize(this.maxOplogSize);
 final OplogFile olf = getOLF();
 try {
  olf.raf.setLength(this.maxOplogSize);
  olf.raf.seek(0);
 } catch (IOException ignore) {
  // TODO: need a warning since this can impact perf.
  // I don't think I need any of this. If setLength throws then
  // the file is still ok.
 }
}

代码示例来源:origin: square/tape

@Private static RandomAccessFile initializeFromFile(File file, boolean forceLegacy)
  throws IOException {
 if (!file.exists()) {
  // Use a temp file so we don't leave a partially-initialized file.
  File tempFile = new File(file.getPath() + ".tmp");
  RandomAccessFile raf = open(tempFile);
  try {
   raf.setLength(INITIAL_LENGTH);
   raf.seek(0);
   if (forceLegacy) {
    raf.writeInt(INITIAL_LENGTH);
   } else {
    raf.writeInt(VERSIONED_HEADER);
    raf.writeLong(INITIAL_LENGTH);
   }
  } finally {
   raf.close();
  }
  // A rename is atomic.
  if (!tempFile.renameTo(file)) {
   throw new IOException("Rename failed!");
  }
 }
 return open(file);
}

代码示例来源:origin: io.takari.maven.plugins/takari-lifecycle-plugin

@Override
public void close() throws IOException {
 long pos = raf.getFilePointer();
 if (pos < raf.length()) {
  modified = true;
  raf.setLength(pos);
 }
 raf.close();
}

代码示例来源:origin: atomix/atomix

@Override
public MappedMemory allocate(int size) {
 try {
  if (file.length() < size) {
   file.setLength(size);
  }
  referenceCount.incrementAndGet();
  return new MappedMemory(channel.map(mode, offset, size), this);
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: com.liferay.portal/com.liferay.portal.kernel

protected long readUntil(long position) throws IOException {
  if (position < _length) {
    return position;
  }
  if (_foundEOF) {
    return _length;
  }
  long lengthToRead = position - _length;
  _randomAccessFileCache.seek(_length);
  byte[] buffer = new byte[1024];
  while (lengthToRead > 0) {
    int bytesRead = _inputStream.read(
      buffer, 0, (int)Math.min(lengthToRead, buffer.length));
    if (bytesRead == -1) {
      _foundEOF = true;
      return _length;
    }
    _randomAccessFileCache.setLength(
      _randomAccessFileCache.length() + bytesRead);
    _randomAccessFileCache.write(buffer, 0, bytesRead);
    lengthToRead -= bytesRead;
    _length += bytesRead;
  }
  return position;
}

代码示例来源:origin: apache/ignite

/**
 * @param name File path.
 * @param size Expected file size. If size is 0, the existing size will be used.
 * @throws IOException If failed to open the file or memory-map it.
 */
public MappedFile(File name, long size) throws IOException {
  file = new RandomAccessFile(name, "rw");
  try {
    if (size == 0)
      size = file.length();
    else
      file.setLength(size);
    addr = map(file, MAP_RW, 0, size);
    this.size = size;
  } catch (IOException e) {
    file.close();
    throw e;
  }
}

代码示例来源:origin: alibaba/mdrill

/**
 * Creates a new ZIP OutputStream writing to a File.  Will use
 * random access if possible.
 * @param file the file to zip to
 * @since 1.14
 * @throws IOException on error
 */
public ZipOutputStream(File file) throws IOException {
  super(null);
  RandomAccessFile _raf = null;
  try {
    _raf = new RandomAccessFile(file, "rw");
    _raf.setLength(0);
  } catch (IOException e) {
    if (_raf != null) {
      try {
        _raf.close();
      } catch (IOException inner) { // NOPMD
        // ignore
      }
      _raf = null;
    }
    out = new FileOutputStream(file);
  }
  raf = _raf;
}

代码示例来源:origin: aragozin/jvm-tools

AbstractLongMap(int size,int idSize,int foffsetSize,int valueSize) throws FileNotFoundException, IOException {
  assert idSize == 4 || idSize == 8;
  assert foffsetSize == 4 || foffsetSize == 8;
  keys = (size * 4L) / 3L;
  ID_SIZE = idSize;
  FOFFSET_SIZE = foffsetSize;
  KEY_SIZE = ID_SIZE;
  VALUE_SIZE = valueSize;
  ENTRY_SIZE = KEY_SIZE + VALUE_SIZE;
  fileSize = keys * ENTRY_SIZE;
  tempFile = File.createTempFile("NBProfiler", ".map"); // NOI18N
  RandomAccessFile file = new RandomAccessFile(tempFile, "rw"); // NOI18N
  if (Boolean.getBoolean("org.netbeans.lib.profiler.heap.zerofile")) {    // NOI18N
    byte[] zeros = new byte[512*1024];
    while(file.length()<fileSize) {
      file.write(zeros);
    }
    file.write(zeros,0,(int)(fileSize-file.length()));
  }
  file.setLength(fileSize);
  setDumpBuffer(file);
  tempFile.deleteOnExit();
}

代码示例来源:origin: apache/kafka

/**
 * Open a channel for the given file
 * For windows NTFS and some old LINUX file system, set preallocate to true and initFileSize
 * with one value (for example 512 * 1025 *1024 ) can improve the kafka produce performance.
 * @param file File path
 * @param mutable mutable
 * @param fileAlreadyExists File already exists or not
 * @param initFileSize The size used for pre allocate file, for example 512 * 1025 *1024
 * @param preallocate Pre-allocate file or not, gotten from configuration.
 */
private static FileChannel openChannel(File file,
                    boolean mutable,
                    boolean fileAlreadyExists,
                    int initFileSize,
                    boolean preallocate) throws IOException {
  if (mutable) {
    if (fileAlreadyExists || !preallocate) {
      return FileChannel.open(file.toPath(), StandardOpenOption.CREATE, StandardOpenOption.READ,
          StandardOpenOption.WRITE);
    } else {
      RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
      randomAccessFile.setLength(initFileSize);
      return randomAccessFile.getChannel();
    }
  } else {
    return FileChannel.open(file.toPath());
  }
}

代码示例来源:origin: apache/flink

@SuppressWarnings("unchecked")
public void open(File inputFile) throws IOException {
  deserializer = (Deserializer<OUT>) (readAsByteArray ? new ByteArrayDeserializer() : new TupleDeserializer());
  inputFile.getParentFile().mkdirs();
  if (inputFile.exists()) {
    inputFile.delete();
  }
  inputFile.createNewFile();
  inputRAF = new RandomAccessFile(inputFile, "rw");
  inputRAF.setLength(mappedFileSizeBytes);
  inputRAF.seek(mappedFileSizeBytes - 1);
  inputRAF.writeByte(0);
  inputRAF.seek(0);
  inputChannel = inputRAF.getChannel();
  fileBuffer = inputChannel.map(FileChannel.MapMode.READ_WRITE, 0, mappedFileSizeBytes);
}

代码示例来源:origin: lealone/Lealone

private synchronized void writeChunkMetaData(int lastChunkId, TreeSet<Long> removedPages) {
  try {
    chunkMetaData.setLength(0);
    chunkMetaData.seek(0);
    chunkMetaData.writeInt(lastChunkId);
    chunkMetaData.writeInt(removedPages.size());
    for (long pos : removedPages) {
      chunkMetaData.writeLong(pos);
    }
    chunkMetaData.writeInt(hashCodeToHostIdMap.size());
    for (String hostId : hashCodeToHostIdMap.values()) {
      chunkMetaData.writeUTF(hostId);
    }
    // chunkMetaData.setLength(4 + 4 + removedPages.size() * 8);
    chunkMetaData.getFD().sync();
  } catch (IOException e) {
    throw panic(DataUtils.newIllegalStateException(DataUtils.ERROR_WRITING_FAILED,
        "Failed to writeChunkMetaData", e));
  }
}

代码示例来源:origin: org.glassfish.external/schema2beans

public void close() throws IOException {
    // Truncate it.
    //System.out.println("truncating to "+randFile.getFilePointer());
    if (randFile.getFilePointer() < randFile.length()) {
      justWrite = true;
      randFile.setLength(randFile.getFilePointer());
    }
    randFile.close();
  }
}

代码示例来源:origin: lealone/Lealone

@Override
public FileChannel truncate(long newLength) throws IOException {
  // compatibility with JDK FileChannel#truncate
  if (readOnly) {
    throw new NonWritableChannelException();
  }
  if (newLength < file.length()) {
    file.setLength(newLength);
  }
  return this;
}

代码示例来源:origin: ome/formats-common

@Override
public void setLength(long length) throws IOException {
 if (raf.length() < length) {
  raf.setLength(length);
 }
 raf.seek(length - 1);
 buffer = null;
}

代码示例来源:origin: smuyyh/BookReader

RandomAccessFile raf = new RandomAccessFile(file, "rw");
  if (skip < 0 || skip > raf.length()) {
    System.out.println("skip error");
    return;
  raf.setLength(raf.length() + b.length);
  for (long i = raf.length() - 1; i > b.length + skip - 1; i--) {
    raf.seek(i - b.length);
    byte temp = raf.readByte();
    raf.seek(i);
    raf.writeByte(temp);
  raf.seek(skip);
  raf.write(b);
  raf.close();
} catch (Exception e) {
  e.printStackTrace();

相关文章