Está en la página 1de 2

import java.io.

*;
import java.lang.*;
public class hola {
public hola() {
}
public static void add(archivo f)throws IOException{
f.add(new registro("Juan",15,12.5f));
f.add(new registro("Alvaro",17,22.5f));
f.add(new registro("Julio",18,32.5f));
f.add(new registro("Cesar",20,42.5f));
}
public static void main(String[] args)throws IOException {
archivo a=new archivo("Hola.dat");
add(a);
a.mostrar();
}
}
class archivo{
RandomAccessFile f;
String fileName;
public archivo(String nombre){
fileName=nombre;
}
void open(String mode)throws IOException{
try{
f=new RandomAccessFile(fileName,mode);
}
catch(IOException e){
f=new RandomAccessFile(fileName,"rw");
}
}
public void add(registro a)throws IOException{
open("rw");
f.seek(f.length());
a.escribir(f);
f.close();
}
public void mostrar()throws IOException{
registro aux=new registro();
open("r");
long n=f.length()/aux.tam();
for(long i=0;i<n;i++){
aux.leer(f);
aux.ver();
}
f.close();
}
}
class registro{
String nombre;
int edad;
float peso;
public registro(){
}
public registro(registro a){
nombre=a.nombre;
edad=a.edad;
peso=a.peso;
}
public registro(String nombre,int edad,float peso){
this.nombre=nombre;
this.edad=edad;
this.peso=peso;
}
public void leer(RandomAccessFile f)throws IOException{
byte b[]=new byte[20];
f.readFully(b);
nombre=new String(b,0);
edad=f.readInt();
peso=f.readFloat();
}
public void escribir(RandomAccessFile f)throws IOException{
byte b[]=new byte[20];
nombre.getBytes(0,nombre.length(),b,0);
f.write(b);
f.writeInt(edad);
f.writeFloat(peso);
}
public long tam(){
return 28;
}
public void ver(){
System.out.println (nombre.trim()+" "+peso+" "+edad);
}
}

También podría gustarte