我有使用RandomAccessFile修改文件中的數據的代碼。
但它不能工作。如何使用java更新數據RandomAccessFile
Scanner sc = new Scanner(System.in);
System.out.println("enter search id");
String search = sc.next().toLowerCase();
try {
file = new RandomAccessFile(new File("HallFile.txt"), "rw");
long FileSize = file.length();
file.seek(0);
long numberOfRecords = FileSize/RECORD;
for (int j = 0; j < numberOfRecords; j++) {
hall_id= file.readInt();
floorNo= file.readInt();
area= file.readInt();
capacity= file.readInt();
rent= file.readInt();
dimonssion= file.readInt();
char temp = '\0';
for(int i=0; i< 20; i++){
temp = file.readChar();
if(temp == '\0') continue;
hall_type += temp;
}
for(int i=0; i< 20; i++){
temp = file.readChar();
if(temp == '\0') continue;
seat_style += temp;
}
for(int i=0; i< 20; i++){
temp = file.readChar();
if(temp == '\0') continue;
facilities += temp;
Integer m = hall_id;
if(search.equals(m.toString()))
{
file.seek(RECORD*j+144);
System.out.println("New Floor NO: ");
floorNo= sc.nextInt();
file.write(floorNo);
System.out.println("Hall area: ");
area= sc.nextInt();
file.write(area);
System.out.println("Hall capacity: ");
capacity= sc.nextInt();
file.write(capacity);
System.out.println("Hall rent per day: ");
rent= sc.nextInt();
file.write(rent);
System.out.println("Hall Type: ");
hall_type= sc.next().toLowerCase();
file.writeUTF(hall_type);
System.out.println("Hall Style: ");
seat_style= sc.next().toLowerCase();
file.writeUTF(seat_style);
System.out.println("Hall Facilities: ");
facilities= sc.next().toLowerCase();
file.writeUTF(facilities);
System.out.println("Hall Dimonssion: ");
dimonssion= sc.nextInt();
file.write(dimonssion);
System.out.println("Saved successfully.");
}
}
file.close();
}} catch (IOException e) {
e.getStackTrace();
System.out.println("error");
}
這些是變量int hall_id,floorNo,area,capacity,rent,dimonssion,lenght,width; String hall_type,seat_style,facilities;並且最終的int RECORD是144 –
在問題的下面應該有一個「編輯」按鈕,您可以在其中添加信息或重新格式化它。另外:你的代碼中沒有按預期工作?怎麼了?應該發生什麼?如果有錯誤,請將異常堆棧追蹤添加到您的問題中。 – zapl
此代碼顯示將添加到文件中的數據,並且我想編輯這些數據,但我對此沒有想法。 –