|
|
@@ -0,0 +1,69 @@ |
|
|
|
package cc.javastudio.raw; |
|
|
|
|
|
|
|
import java.io.*; |
|
|
|
import java.nio.charset.StandardCharsets; |
|
|
|
|
|
|
|
public class FileHandler implements Closeable { |
|
|
|
private final int INT_LENGTH = 4; |
|
|
|
private final byte BYTE_LENGTH = 1; |
|
|
|
private RandomAccessFile dbFile; |
|
|
|
|
|
|
|
public FileHandler(String dbFileName) throws FileNotFoundException { |
|
|
|
dbFile = new RandomAccessFile(dbFileName,"rw"); |
|
|
|
} |
|
|
|
|
|
|
|
public void add(String name, int age, String address, String licencePlate, String desciption) throws IOException { |
|
|
|
dbFile.seek(dbFile.length()); |
|
|
|
int recordLength = INT_LENGTH + name.length() + |
|
|
|
INT_LENGTH + |
|
|
|
INT_LENGTH + address.length() + |
|
|
|
INT_LENGTH + licencePlate.length() + |
|
|
|
INT_LENGTH + desciption.length(); |
|
|
|
|
|
|
|
dbFile.writeBoolean(false); |
|
|
|
dbFile.writeInt(recordLength); |
|
|
|
dbFile.writeInt(name.length()); |
|
|
|
dbFile.write(name.getBytes()); |
|
|
|
dbFile.writeInt(age); |
|
|
|
dbFile.writeInt(address.length()); |
|
|
|
dbFile.write(address.getBytes()); |
|
|
|
dbFile.writeInt(licencePlate.length()); |
|
|
|
dbFile.write(licencePlate.getBytes()); |
|
|
|
dbFile.writeInt(desciption.length()); |
|
|
|
dbFile.write(desciption.getBytes()); |
|
|
|
} |
|
|
|
|
|
|
|
public Person readRow(int rowNUmber) throws IOException { |
|
|
|
Person person = new Person(); |
|
|
|
byte [] rawData = readRawRecord(0); |
|
|
|
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(rawData)); |
|
|
|
byte[] b = new byte[stream.readInt()]; |
|
|
|
stream.read(b); |
|
|
|
person.name = new String(b); |
|
|
|
|
|
|
|
return person; |
|
|
|
} |
|
|
|
|
|
|
|
private byte[] readRawRecord(int rowNumber) throws IOException { |
|
|
|
int pos = 0; |
|
|
|
byte [] data; |
|
|
|
dbFile.seek(pos); |
|
|
|
|
|
|
|
if(dbFile.readBoolean()){ |
|
|
|
data = new byte[0]; |
|
|
|
} |
|
|
|
else { |
|
|
|
pos+= BYTE_LENGTH; |
|
|
|
dbFile.seek(pos); |
|
|
|
int recordLength = dbFile.readInt(); |
|
|
|
pos += INT_LENGTH; |
|
|
|
data = new byte[recordLength]; |
|
|
|
dbFile.read(data); |
|
|
|
} |
|
|
|
return data; |
|
|
|
} |
|
|
|
|
|
|
|
public void close() throws IOException { |
|
|
|
dbFile.close(); |
|
|
|
} |
|
|
|
} |