[英]how to Write / Replace Object to text file - Java
如何替换文本文件中的 object 并将其保存到文本文件中???
首先,我添加了单独的房间。
for (int i = 0; i < lines.size() - 1; i++){
String[] words = lines.get(i).split(" ");
var room = new Room();
room.roomNum = Integer.parseInt(words[0]);
room.roomType = (words[1]);
room.roomPrice = Double.parseDouble(words[2]);
room.hasBalcony = Boolean.parseBoolean(words[3]);
room.hasLounge = Boolean.parseBoolean(words[4]);
room.eMail = (words[5]);
rooms.add(room);
}
然后我在文本文件中搜索一个特定的房间,并将 selectedRoom.eMail 替换为reserveEmail。
System.out.println("\n-- ROOM RESERVATION --");
System.out.println("Please enter the room number you wish to reserve");
Room selectedRoom = null;
var searchRoomNum = input.nextInt();
for(int i = 0; i < rooms.size(); i++){
if(rooms.get(i).roomNum == searchRoomNum){
selectedRoom = rooms.get(i);
}
}
if(selectedRoom.eMail.contentEquals("free")) {
System.out.println("Please Enter your email");
var reserveEmail = input.next();
selectedRoom.eMail = reserveEmail;
System.out.println("Thanks, this room has been reserved");
return;
}
我需要知道如何将此更改保存到它来自的文本文件而不覆盖整个文件。
根据文件的大小,将其加载到 memory 中,将其解析为 Room 对象并覆盖您的更改可能会更容易。
如果我的代码有错误,我深表歉意,但我在移动设备上。 它应该为您提供让它运行的通用算法。
导入扫描仪
import java.util.Scanner;
一般更新过程
// Load to memory
Scanner scn = new Scanner(new File(“C:\Users\me\Desktop\test.txt”));
// Create new list of rooms
List<Room> roomList = new ArrayList<Room>();
// Begin parsing
while (scn.HasNextLine()) {
String currentLine = scn.nextLine();
String[] roomAttrs = currentLine.split(“ ”);
Room currentRoom = new Room();
currentRoom.roomNum = Integer.parseInt(roomAttrs[0]);
currentRoom.roomType = roomAttrs[1];
currentRoom.roomPrice = Double.parseDouble(roomAttrs[2]);
currentRoom.hasBalcony = Boolean.parseBoolean(roomAttrs[3]);
currentRoom.hasLounge = Boolean.parseBoolean(roomAttrs[4]);
currentRoom.eMail = roomAttrs[5];
// make your changes to the room here
roomList.add(currentRoom);
}
// reuse code for writing to text here, either delete file or clear it
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.