0
내 프로그램에 대한 정보를 저장할 임의 액세스 파일을 사용하고 싶습니다. 파일에서 문자열과 열거 형 변수의 arraylist를 읽고 쓸 수있는 방법이 있습니까? (내가 읽고에 이진 파일에서 작성하는 직렬화 가능 인터페이스를 사용하여이 작업을 수행 할 수 있다는 것을 알고 있지만 랜덤 액세스 파일에 대한 솔루션을 찾고 있어요.)랜덤 액세스 파일과 문자열 및 열거 변수의 arraylist 읽기 및 쓰기
참조 코드 :
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;
}
}
작동하지 않는 기능은 무엇입니까? 또한,'RandomAccessFile'과 데이터베이스 또는 직렬화를 사용하는 특별한 이유가 있습니까? Embedded Derby는 매우 유용합니다. – Dave
램 파일에서 arraylist와 enum을 읽고 쓰는 법을 모르겠습니다. – trs