Tabnine Logo
RandomAccessFile
Code IndexAdd Tabnine to your IDE (free)

How to use
RandomAccessFile
in
java.io

Best Java code snippets using java.io.RandomAccessFile (Showing top 20 results out of 17,829)

Refine searchRefine arrow

  • FileChannel
  • FileLock
  • MappedByteBuffer
  • AbstractInterruptibleChannel
origin: google/guava

private static MappedByteBuffer mapInternal(File file, MapMode mode, long size)
  throws IOException {
 checkNotNull(file);
 checkNotNull(mode);
 Closer closer = Closer.create();
 try {
  RandomAccessFile raf =
    closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
  FileChannel channel = closer.register(raf.getChannel());
  return channel.map(mode, 0, size == -1 ? channel.size() : size);
 } catch (Throwable e) {
  throw closer.rethrow(e);
 } finally {
  closer.close();
 }
}
origin: apache/storm

private byte[] readFile(File file) throws IOException {
  RandomAccessFile raf = new RandomAccessFile(file, "r");
  byte[] buffer = new byte[(int) raf.length()];
  raf.readFully(buffer);
  raf.close();
  return buffer;
}
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: hankcs/HanLP

private int nextId() throws IOException
{
  if (raf.length() - raf.getFilePointer() >= 4)
  {
    int id = raf.readInt();
    return id < 0 ? id : table[id];
  }
  return -2;
}
origin: prestodb/presto

  @Override
  protected void readInternal(long position, byte[] buffer, int bufferOffset, int bufferLength)
      throws IOException
  {
    input.seek(position);
    input.readFully(buffer, bufferOffset, bufferLength);
  }
}
origin: jenkinsci/jenkins

public void skip(long start) throws IOException {
  file.seek(file.getFilePointer()+start);
}
origin: libgdx/libgdx

void addPatchFile(String zipFileName) throws IOException {
  File file = new File(zipFileName);
  RandomAccessFile f = new RandomAccessFile(file, "r");
  long fileLength = f.length();
    f.close();
    throw new java.io.IOException();
  f.seek(0);
  f.seek(searchStart);
  ByteBuffer bbuf = ByteBuffer.allocate((int) readAmount);
  byte[] buffer = bbuf.array();
  f.readFully(buffer);
  bbuf.order(ByteOrder.LITTLE_ENDIAN);
  MappedByteBuffer directoryMap = f.getChannel().map(
      FileChannel.MapMode.READ_ONLY, dirOffset, dirSize);
  directoryMap.order(ByteOrder.LITTLE_ENDIAN);
    if (directoryMap.getInt(currentOffset) != kCDESignature) {
      Log.w(LOG_TAG, "Missed a central dir sig (at " + currentOffset
          + ")");
        .getShort(currentOffset + kCDENameLen) & 0xffff;
    int extraLen = directoryMap.getShort(currentOffset + kCDEExtraLen) & 0xffff;
    int commentLen = directoryMap.getShort(currentOffset
origin: graphhopper/graphhopper

public static void main(String[] args) throws IOException {
  // trying FileLock mechanics in different processes
  File file = new File("tmp.lock");
  file.createNewFile();
  FileChannel channel = new RandomAccessFile(file, "r").getChannel();
  boolean shared = true;
  FileLock lock1 = channel.tryLock(0, Long.MAX_VALUE, shared);
  System.out.println("locked " + lock1);
  System.in.read();
  System.out.println("release " + lock1);
  lock1.release();
}
origin: stackoverflow.com

 public void insert(String filename, long offset, byte[] content) {
 RandomAccessFile r = new RandomAccessFile(new File(filename), "rw");
 RandomAccessFile rtemp = new RandomAccessFile(new File(filename + "~"), "rw");
 long fileSize = r.length();
 FileChannel sourceChannel = r.getChannel();
 FileChannel targetChannel = rtemp.getChannel();
 sourceChannel.transferTo(offset, (fileSize - offset), targetChannel);
 sourceChannel.truncate(offset);
 r.seek(offset);
 r.write(content);
 long newOffset = r.getFilePointer();
 targetChannel.position(0L);
 sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset));
 sourceChannel.close();
 targetChannel.close();
}
origin: gocd/gocd

public synchronized void writeToConfigXmlFile(String content) {
  FileChannel channel = null;
  FileOutputStream outputStream = null;
  FileLock lock = null;
  try {
    RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw");
    channel = randomAccessFile.getChannel();
    lock = channel.lock();
    randomAccessFile.seek(0);
    randomAccessFile.setLength(0);
    outputStream = new FileOutputStream(randomAccessFile.getFD());
    IOUtils.write(content, outputStream, UTF_8);
  } catch (Exception e) {
    throw new RuntimeException(e);
  } finally {
    if (channel != null && lock != null) {
      try {
        lock.release();
        channel.close();
        IOUtils.closeQuietly(outputStream);
      } catch (IOException e) {
        LOGGER.error("Error occured when releasing file lock and closing file.", e);
      }
    }
  }
}
origin: bumptech/glide

 raf = new RandomAccessFile(file, "r");
 channel = raf.getChannel();
 return channel.map(FileChannel.MapMode.READ_ONLY, 0, fileLength).load();
} finally {
 if (channel != null) {
  try {
   channel.close();
  } catch (IOException e) {
   raf.close();
  } catch (IOException e) {
origin: pxb1988/dex2jar

public ZipFile(File fd) throws IOException {
  RandomAccessFile randomAccessFile = new RandomAccessFile(fd, "r");
  file = randomAccessFile;
  raf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, fd.length());
  readCentralDir();
}
origin: stackoverflow.com

try {
   // Get a file channel for the file
   File file = new File("filename");
   FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
   // Use the file channel to create a lock on the file.
   // This method blocks until it can retrieve the lock.
   FileLock lock = channel.lock();
   /*
     use channel.lock OR channel.tryLock();
   */
   // Try acquiring the lock without blocking. This method returns
   // null or throws an exception if the file is already locked.
   try {
     lock = channel.tryLock();
   } catch (OverlappingFileLockException e) {
     // File is already locked in this thread or virtual machine
   }
   // Release the lock - if it is not null!
   if( lock != null ) {
     lock.release();
   }
   // Close the file
   channel.close();
 } catch (Exception e) {
 }
origin: stackoverflow.com

 try {
int shmSize = 1024;
RandomAccessFile file = new RandomAccessFile("shm.raw","rw");

// inialize file size
if(file.length() < shmSize) {
 byte[] tmp = new byte[shmSize];
 file.write(tmp);
 file.seek(0); // seek back to start of file.
}

// memory-map file.
FileChannel ch = file.getChannel();
MappedByteBuffer shm = ch.map(FileChannel.MapMode.READ_WRITE, 0, shmSize);
ch.close(); // channel not needed anymore.
shm.load(); // force file into physical memory.

// now use the ByteBuffer's get/put/position methods to read/write the shared memory

} catch(Exception e) { e.printStackTrace(); }
origin: Codecademy/EventHub

public static MappedByteBuffer expandBuffer(String filename, MappedByteBuffer buffer,
  long newSize) {
 buffer.force();
 int oldPosition = buffer.position();
 try (RandomAccessFile raf = new RandomAccessFile(filename, "rw")) {
  raf.setLength(newSize);
  buffer = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, raf.length());
  buffer.position(oldPosition);
  return buffer;
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}
origin: apache/ignite

  @Override public void run() {
    try {
      RandomAccessFile raf = new RandomAccessFile(file, "rw");
      System.out.println("Getting lock (parallel thread)...");
      FileLock lock = raf.getChannel().lock();
      System.out.println("Obtained lock (parallel tread): " + lock);
      lock.release();
    }
    catch (Throwable e) {
      e.printStackTrace();
    }
  }
});
origin: stackoverflow.com

 public void writeToFileNIOWay2(File file) throws IOException {
  final int numberOfIterations = 1000000;
  final String messageToWrite = "This is a test üüüüüüööööö";
  final byte[] messageBytes = messageToWrite.
      getBytes(Charset.forName("ISO-8859-1"));
  final long appendSize = numberOfIterations * messageBytes.length;
  final RandomAccessFile raf = new RandomAccessFile(file, "rw");
  raf.seek(raf.length());
  final FileChannel fc = raf.getChannel();
  final MappedByteBuffer mbf = fc.map(FileChannel.MapMode.READ_WRITE, fc.
      position(), appendSize);
  fc.close();
  for (int i = 1; i < numberOfIterations; i++) {
    mbf.put(messageBytes);
  }
}
origin: libgdx/libgdx

public long length () {
  try {
    if (!exists()) {
      return 0;
    }
    RandomAccessFile raf = new RandomAccessFile(this, "r");
    long len = raf.length();
    raf.close();
    return len;
  } catch (IOException e) {
    return 0;
  }
}
origin: Codecademy/EventHub

 @Override
 public DmaIdList build(String filename) {
  try {
   File file = new File(filename);
   if (!file.exists()) {
    //noinspection ResultOfMethodCallIgnored
    file.getParentFile().mkdirs();
    //noinspection ResultOfMethodCallIgnored
    file.createNewFile();
    try (RandomAccessFile raf = new RandomAccessFile(new File(filename), "rw")) {
     raf.setLength(DmaIdList.META_DATA_SIZE + defaultCapacity * DmaIdList.SIZE_OF_DATA);
    }
   }
   try (RandomAccessFile raf = new RandomAccessFile(new File(filename), "rw")) {
    FileChannel channel = raf.getChannel();
    MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, raf.length());
    int numRecords = buffer.getInt();
    int capacity = (int) (raf.length() - DmaIdList.META_DATA_SIZE) / DmaIdList.SIZE_OF_DATA;
    buffer.position(DmaIdList.META_DATA_SIZE + numRecords * DmaIdList.SIZE_OF_DATA);
    return new DmaIdList(filename, buffer, numRecords, capacity);
   }
  } catch (IOException e) {
   throw new RuntimeException(e);
  }
 }
}
origin: apache/incubator-pinot

RandomAccessFile raf = new RandomAccessFile(FILE_NAME, "rw");
mmappedByteBuffer = raf.getChannel().map(MapMode.READ_WRITE, 0L, raf.length());
mmappedByteBuffer.load();
java.ioRandomAccessFile

Javadoc

Allows reading from and writing to a file in a random-access manner. This is different from the uni-directional sequential access that a FileInputStream or FileOutputStream provides. If the file is opened in read/write mode, write operations are available as well. The position of the next read or write operation can be moved forwards and backwards after every operation.

Most used methods

  • <init>
    Constructs a new RandomAccessFile based on the file named fileName and opens it according to the acc
  • close
    Closes this file.
  • seek
    Moves this file's file pointer to a new position, from where following read, write or skip operation
  • getChannel
    Gets this file's FileChannel object. The file channel's FileChannel#position() is the same as this f
  • length
    Returns the length of this file in bytes.
  • read
    Reads up to byteCount bytes from the current position in this file and stores them in the byte array
  • write
    Writes byteCount bytes from the byte array buffer to this file, starting at the current file pointer
  • setLength
    Sets the length of this file to newLength. If the current file is smaller, it is expanded but the co
  • getFilePointer
    Gets the current position within this file. All reads and writes take place at the current file poin
  • readFully
    Reads byteCount bytes from this stream and stores them in the byte array dst starting at offset. If
  • getFD
    Gets this file's FileDescriptor. This represents the operating system resource for this random acces
  • readInt
    Reads a big-endian 32-bit integer from the current position in this file. Blocks until four bytes ha
  • getFD,
  • readInt,
  • writeInt,
  • readByte,
  • readLong,
  • readLine,
  • skipBytes,
  • writeLong,
  • writeByte,
  • writeBytes

Popular in Java

  • Updating database using SQL prepared statement
  • addToBackStack (FragmentTransaction)
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • getResourceAsStream (ClassLoader)
  • InputStreamReader (java.io)
    A class for turning a byte stream into a character stream. Data read from the source input stream is
  • URI (java.net)
    A Uniform Resource Identifier that identifies an abstract or physical resource, as specified by RFC
  • Comparator (java.util)
    A Comparator is used to compare two objects to determine their ordering with respect to each other.
  • Manifest (java.util.jar)
    The Manifest class is used to obtain attribute information for a JarFile and its entries.
  • ZipFile (java.util.zip)
    This class provides random read access to a zip file. You pay more to read the zip file's central di
  • Options (org.apache.commons.cli)
    Main entry-point into the library. Options represents a collection of Option objects, which describ
  • Top plugins for Android Studio
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now