如何在文本文件中查找特定行,并将其替换为其他行

时间:2014-04-13 13:38:37

标签: java replace

好的,我正在尝试搜索yaml文件以查找特定的代码行

yaml文件通常看起来像这样,但它可以加上或减去其他几行:

timestamps:
  login: 1397256621980
  logout: 1397267743528
  lastteleport: 1397265370690
ipAddress: 127.0.0.1
lastlocation:
  world: world
  x: -208.52097206207856
  y: 64.0
  z: -367.26689797238714
  yaw: 199.81995
  pitch: 11.099998
logoutlocation:
  world: world
  x: -160.36469909073216
  y: 64.0
  z: -422.31472024960175
  yaw: 235.05505
  pitch: 30.90003
money: '1.0'
socialspy: true
afk: false
uuid: b735fgb3-9830-3556-bdf3-5abdd9206368
powertools: {}

我正在尝试替换

socialspy: true

socialspy: false
但是大约30分钟后我没有运气。我知道扫描仪的基本知识,但对文件编写者等一无所知。

1 个答案:

答案 0 :(得分:0)

逐行阅读文件并检查bad string是否将其写入新文件:

try {
String oldFile = "oldFileNname";
String newFile = "newFileName";
PrintWriter f = new PrintWriter(new FileWriter(newFile));


BufferedReader br = new BufferedReader(new FileReader(oldFile));
String line;
while ((line = br.readLine()) != null) {

    if (line.equals("socialspy: true")) {
        f.println("socialspy: false");
    }
    else {
        f.println(line);
    }
}
br.close();
f.close();
}catch (IOException e) {
    //OMG Exception again!
}