簡體   English   中英

替換txt文件中的特定行

[英]Replace specific line in txt file

我正在從文本文件中將有關預訂系統座位的數據讀入ArrayList中。 一行不能放入變量fileLine中。 文件行是從每個“,”中拆分出來的,並放入稱為組件的數組中。 然后將組件放入對象中。

txt文件示例

1a, first, window, notable, forward, noeoa, false, null 
1b, first, nowindow, notable, forward, noeoa, false, null
2a, first, window, notable, forward, eoa, false, null
2b, first, nowindow, notable, forward, eoa, false, null
3a, first, window, table, forward, noeoa, false, null
3b, first, nowindow, table, forward, noeoa, false, null

然后,這將進入if語句,以檢查座位是否合適,是否要將false更改為true並將乘客姓名添加為null,但僅在合適的座位上。 我想知道是否有任何方法可以覆蓋文本文件中的特定行。 行號存儲在名為lineCounter的變量中

Scanner inFile = new Scanner(
            new FileReader("seats.txt"));
    ArrayList<seat> seats = new ArrayList<>();
    Boolean var = false;

    while (inFile.hasNext()) {

        String fileLine = inFile.nextLine();

        seats.add(new seat(fileLine));

        if (seat.classs.equals(seatClass) && (seat.window.equals(seatLocation) || seat.both != null)
                && seat.table.equals(seatTable) && seat.face.equals(seatFace) && seat.EOA.equals(seatEOA)
                && seat.resevered == false) {
            System.out.print("Seat " + seat.seat + " Booked");
            var = true;
            seat.resevered = true;
            seat.resName = emailSelect;


        }

在哪里fileLine被分割

public seat(String fileLine)
{

String[] components = fileLine.split(",");

if (components[7].equals("null"))
    this.resName = null;
else
    this.resName = components[7];

if (components[2].equals(" both"))
    this.both = "notnull";
else
    this.both = null;

this.seat = (components[0].trim());
this.classs = (components[1].trim());
this.window = (components[2].trim());
this.table = (components[3].trim());
this.face = (components[4].trim());
this.EOA = (components[5].trim());
this.resevered = Boolean.parseBoolean(components[6].trim());

}

假設您要覆蓋文件中的數據,請在修改您的代碼后查看下面編寫的代碼

Scanner inFile = new Scanner(
        new FileReader("seats.txt"));
ArrayList<seat> seats = new ArrayList<>();
Boolean var = false;
int count=0;
while (inFile.hasNext()) {

    String fileLine = inFile.nextLine();
    count++;

    if(count==lineCounter){
       fileLine=fileLine.replace(oldValue,overWriteValue);
    }
    seats.add(new seat(fileLine));

    if (seat.classs.equals(seatClass) && (seat.window.equals(seatLocation) || seat.both != null)
            && seat.table.equals(seatTable) && seat.face.equals(seatFace) && seat.EOA.equals(seatEOA)
            && seat.resevered == false) {
        System.out.print("Seat " + seat.seat + " Booked");
        var = true;
        seat.resevered = true;
        seat.resName = emailSelect;


    }

解決方法很簡單,我希望您尋找這個,否則讓我知道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM