如何将对象写入/替换为文本文件-java

mlnl4t2r  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(401)

如何替换文本文件中的对象并将其保存到文本文件???
首先我要添加单独的房间。

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替换为reservemail。

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;
}

我需要知道如何将此更改保存到它来自的文本文件中,而不覆盖整个文件。

vyu0f0g1

vyu0f0g11#

根据文件的大小,简单地将其加载到内存中、将其解析到文件室对象中以及覆盖更改可能会更容易。
我很抱歉,如果我的代码有错误,但我在移动。它应该给你一个通用的算法让它运行。
导入扫描仪

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

相关问题