繁体   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