Re: Reading from a Random Access File
Here's yet another.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Random;
/**
* Alternating Byte Format
*
* Each (two byte) record consists
* of two (one byte) fields.
*
* Field 1 RoomNumber.
* Field 2 ComputerCount.
*
* Each field will represent an
* integer value between 0-255.
*
*/
public class RandomAccess
{
public static void main(String[] args)
{
writeData();
readData();
}
static void writeData()
{
File f = new File("Class Room Details.abf");
Random rnd = new Random();
byte[] fileContents = new byte[100];
rnd.nextBytes(fileContents);
try
{
FileOutputStream fos = new FileOutputStream(f);
fos.write(fileContents);
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
static void readData()
{
int roomNumber;
int computerCount;
try
{
File f = new File("Class Room Details.abf");
RandomAccessFile raf = new RandomAccessFile(f, "r");
while (raf.getFilePointer() < raf.length())
{
roomNumber = raf.readByte() & 0xFF;
computerCount = raf.readByte() & 0xFF;
shutdownComputers(roomNumber, computerCount);
}
raf.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
static void shutdownComputers(int room, int count)
{
System.out.println("Shutdown " + count +
" computers in Room " + room + ".\tBye");
}
}