archivo de acceso aleatorio en java
-
11-07-2019 - |
Pregunta
Tengo los siguientes campos:
- Control de inventario (registro de 16 bytes)
- Código de identificación del producto (int & # 8211; 4 bytes)
- Cantidad en stock (int & # 8211; 4 bytes)
- Precio (doble & # 8211; 8 bytes)
¿Cómo creo un archivo de acceso aleatorio de longitud fija usando las longitudes anteriores? Intenté algunos ejemplos en línea, pero obtengo una excepción EOF o valores de dirección aleatorios cuando intento acceder a ellos.
Intenté algunos ejemplos más y no pude entender muy bien el concepto. Estoy probando un proyecto con él e intentaré explorar más sobre él.
Aquí hay algunos datos de ejemplo. Puede haber agujeros en los datos donde No. en stock
podría ser 23 == 023
.
Quantity
ID. No. In Stock Price
------- -------- ------
1001 476 $28.35
1002 240 $32.56
1003 517 $51.27
1004 284 $23.75
1005 165 $32.25
Gracias por la ayuda.
Solución
java.io.RandomAccessFile es la clase que estás buscando. Aquí hay un ejemplo de implementación (probablemente querrás escribir algunas pruebas unitarias, como no lo he hecho :)
package test;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Raf {
private static class Record{
private final double price;
private final int id;
private final int stock;
public Record(int id, int stock, double price){
this.id = id;
this.stock = stock;
this.price = price;
}
public void pack(int n, int offset, byte[] array){
array[offset + 0] = (byte)(n & 0xff);
array[offset + 1] = (byte)((n >> 8) & 0xff);
array[offset + 2] = (byte)((n >> 16) & 0xff);
array[offset + 3] = (byte)((n >> 24) & 0xff);
}
public void pack(double n, int offset, byte[] array){
long bytes = Double.doubleToRawLongBits(n);
pack((int) (bytes & 0xffffffff), offset, array);
pack((int) ((bytes >> 32) & 0xffffffff), offset + 4, array);
}
public byte[] getBytes() {
byte[] record = new byte[16];
pack(id, 0, record);
pack(stock, 4, record);
pack(price, 8, record);
return record;
}
}
private static final int RECORD_SIZE = 16;
private static final int N_RECORDS = 1024;
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile(args[0], "rw");
try{
raf.seek(RECORD_SIZE * N_RECORDS);
raf.seek(0);
raf.write(new Record(1001, 476, 28.35).getBytes());
raf.write(new Record(1002, 240, 32.56).getBytes());
} finally {
raf.close();
}
}
}
Otros consejos
Con las versiones recientes de Java, puede administrar archivos de acceso aleatorio usando FileChannel. La interfaz SeekableByteChannel define métodos que le permiten cambiar la posición del puntero en la entidad de destino como el archivo al que está conectado el canal. FileChannel implementa SeekableByteChannel que le permite administrar archivos de acceso aleatorio utilizando canales. Los métodos tamaño, posición, truncamiento le permiten leer y escribir archivos al azar.
ver http://www.zoftino.com/java-random-access- archivos para detalles y ejemplos.