替换txt文件中的特定行

时间:2016-04-07 17:48:25

标签: java class object text filewriter

我正在从文本文件和ArrayList中读取有关预订系统席位的数据。将一行放入变量fileLine中。文件行是从每个","分开的。并放入一个名为components的数组。然后将组件放入对象中。

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());

}

1 个答案:

答案 0 :(得分:-1)

假设您想要从文件覆盖数据,请查看我在修改您的文件后编写的代码

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;


    }

解决方案是直截了当的,我希望你能找到这个或者让我知道。

相关问题