Java Tutorial/File/RandomAccessFile

Материал из Java эксперт
Версия от 05:19, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Appending data to existing file

import java.io.File;
import java.io.RandomAccessFile;
public class Main {
  public static void append(String fileName, String text) throws Exception {
    File f = new File(fileName);
    long fileLength = f.length();
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(fileLength);
    raf.writeBytes(text);
    raf.close();
  }
  public static void append(String fileName, byte[] bytes) throws Exception {
    File f = new File(fileName);
    long fileLength = f.length();
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(fileLength);
    raf.write(bytes);
    raf.close();
  }
  public static void main(String[] args) throws Exception {
    append("c:\\tmp.txt", "Appended Data");
    append("c:\\tmp.bin", "Appended Data".getBytes());
  }
}





Employs RandomAccessFile to store ints and changes the value of the third int.

import java.io.IOException;
import java.io.RandomAccessFile;
public class MainClass {
  public static void main(String[] args) {
    try {
      RandomAccessFile raf = new RandomAccessFile("c:\\temp\\RAFsample.txt", "rw");
      raf.writeInt(10);
      raf.writeInt(43);
      raf.writeInt(88);
      raf.writeInt(455);
      // change the 3rd integer from 88 to 99
      raf.seek((3 - 1) * 4);
      raf.writeInt(99);
      raf.seek(0); // go to the first integer
      int i = raf.readInt();
      while (i != -1) {
        System.out.println(i);
        i = raf.readInt();
      }
      raf.close();
    } catch (IOException e) {
    }
  }
}





Getting FileChannel from RandomAccessFile

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
  private static final int BSIZE = 1024;
  public static void main(String[] args) throws Exception {
    FileChannel fc = new RandomAccessFile("data.txt", "rw").getChannel();
    fc.position(fc.size());
    fc.write(ByteBuffer.wrap("Some more".getBytes()));
    fc.close();
  }
}





RandomAccessFile Introduction

  1. A RandomAccessFile employs an internal pointer that points to the next byte to read.
  2. This pointer is zero-based and the first byte is indicated by index 0.
  3. When first created, a RandomAccessFile points to the first byte.
  4. You can change the pointer"s position by invoking the seek method.
  5. The skipBytes method moves the pointer by the specified number of bytes.
  6. If skipping offset number of bytes would pass the end of file, the internal pointer will only move to as much as the end of file.
  7. The skipBytes method returns the actual number of bytes skipped.

When opening a file using a RandomAccessFile, you can choose whether to open it read-only or read write.



public RandomAccessFile (File file, String mode) throws FileNotFoundException
public RandomAccessFile (String filePath, String mode) throws FileNotFoundException





Seek in RandomAccessFile

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class MainClass {
  public static void main(String[] args) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(new File("temp.tmp"), "rw");
    raf.writeInt(1);
    for (int i = 0; i < 10; i++) {
      raf.seek(raf.length() - 4);
      raf.writeInt(raf.readInt());
    }
    raf.close();
  }
}





Test file pointer manipulation between FileChannel and RandomAccessFile objects.

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
public class MainClass {
  public static void main(String[] argv) throws IOException {
    RandomAccessFile randomAccessFile = new RandomAccessFile("test.dat", "r");
    randomAccessFile.seek(1000);
    FileChannel fileChannel = randomAccessFile.getChannel();
    // This will print "1000"
    System.out.println("file pos: " + fileChannel.position());
    randomAccessFile.seek(500);
    // This will print "500"
    System.out.println("file pos: " + fileChannel.position());
    fileChannel.position(200);
    // This will print "200"
    System.out.println("file pos: " + randomAccessFile.getFilePointer());
  }
}





Use RandomAccessFile to reverse a file

import java.io.RandomAccessFile;
public class Main {
  public static void main(String[] argv) throws Exception {
    RandomAccessFile raf = new RandomAccessFile("a.dat", "rw");
    int x, y;
    for (long i = 0, j = raf.length() - 1; i < j; i++, j--) {
      raf.seek(i);
      x = raf.read();
      raf.seek(j);
      y = raf.read();
      raf.seek(j);
      raf.write(x);
      raf.seek(i);
      raf.write(y);
    }
    raf.close();
  }
}





Use RandomAccessFile to save and read

import java.io.IOException;
import java.io.RandomAccessFile;
public class MainClass {
  public static void main(String[] args) throws IOException {
    RandomAccessFile rf = new RandomAccessFile("test.dat", "rw");
    for (int i = 0; i < 10; i++)
      rf.writeDouble(i * 1.414);
    rf.close();
    rf = new RandomAccessFile("test.dat", "rw");
    rf.seek(5 * 8);
    rf.writeDouble(47.0001);
    rf.close();
    rf = new RandomAccessFile("test.dat", "r");
    for (int i = 0; i < 10; i++)
      System.out.println("Value " + i + ": " + rf.readDouble());
    rf.close();
  }
}





Write int to RandomAccessFile using FileChannel

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
  public static void main(String[] args) throws IOException {
    FileChannel fc = new RandomAccessFile("temp.tmp", "rw").getChannel();
    IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()).asIntBuffer();
    for (int i = 0; i < 10; i++)
      ib.put(i);
    fc.close();
  }
}