我愿使用随机查阅文件储存我的节目信息。 是否有办法读写从档案中和从档案中抽取的阵列和 variables变量清单。 (我知道,我可以采用一个可以读写的接口,阅读和书写双亲档案,但我正在寻找随机查阅档案的解决办法。)
参看法典:
public Book(RandomAccessFile file) throws IOException {
// set up Item based on data stored in data disk file
try {
this.ISBN=file.readLong();
this.title = readCharacters(file, 30);
this.publicationDate.set(file.readInt(), file.readInt(), file.readInt());// year month date
this.publisher = readCharacters(file, 30);
this.authorNames= //insert method to read in arraylist of Strings
this.salePrice=file.readDouble();
this.bookCategory=//insert method to read in enum
} catch (IOException io) {
throw io;
}
}
private String readCharacters (RandomAccessFile dataFile,int numChars)
throws IOException{
//reads a specific number of characters and places text in String field
char[] data = new char[numChars];
String field;
try{
for (int i=0;i<numChars;i++)
data[i]= dataFile.readChar();
//now place data into the field
field = new String (data);
field = field.trim(); //get rid of trailing spaces
}
catch(IOException io){
throw io;
}
return field;
}
public void writeToFile(String fileName,long location)throws Exception{
try{
RandomAccessFile invFile =
new RandomAccessFile(fileName,"rw");
//seek to correct record in file
invFile.seek(location);
//now write out the record
//write out the data in fixed length fields
//String fields must be truncated if too large
//or padded with blanks if too small
invFile.writeLong(ISBN);
writeCharacters(invFile,title,30);
invFile.writeInt(publicationDate.YEAR);
invFile.writeInt(publicationDate.MONTH);
invFile.writeInt(publicationDate.DAY_OF_MONTH);
writeCharacters(invFile,publisher,30);
//insert method to write arraylist of authorNames that are Strings
invFile.writeDouble(salePrice);
//insert method to write out bookCategory which is an enumerated type
invFile.close();
}
private void writeCharacters(RandomAccessFile invFile,
String data, int numChars)throws IOException{
char[] stringValue;
String dataChars;
try{
//assume data has the complete number of characters
dataChars = data.substring(0,numChars);
invFile.writeChars(dataChars);
}
catch(IndexOutOfBoundsException e){
//data has less number of characters, must be padded with blanks
dataChars = data.substring(0,data.length());
invFile.writeChars(dataChars);
//now add extra blanks
for (int i=0; i<numChars-dataChars.length();i++)
invFile.writeChar( );
}
catch(IOException io){
throw io;
}
}