原文本内容:
2020-01-21 08:31:08.520 [main] INFO logbackCfg.App -秦时明月汉时关 2020-01-21 08:31:08.521 [main] ERROR logbackCfg.App -万里长征人未还 2020-01-21 08:31:08.521 [main] DEBUG logbackCfg.App -但使龙城飞将在 2020-01-21 08:31:08.521 [main] TRACE logbackCfg.App -不教胡马度阴山 2020-01-21 08:31:10.311 [main] INFO logbackCfg.App2 -九里山前作战场 2020-01-21 08:31:10.317 [main] ERROR logbackCfg.App2 -牧童拾得旧刀枪 2020-01-21 08:31:10.317 [main] DEBUG logbackCfg.App2 -微风吹皱乌江水 2020-01-21 08:31:10.317 [main] TRACE logbackCfg.App2 -恰似虞姬别霸王 2020-01-21 08:31:13.521 [main] INFO logbackCfg.App -秦时明月汉时关 2020-01-21 08:31:13.521 [main] ERROR logbackCfg.App -万里长征人未还 2020-01-21 08:31:13.521 [main] DEBUG logbackCfg.App -但使龙城飞将在 2020-01-21 08:31:13.521 [main] TRACE logbackCfg.App -不教胡马度阴山 2020-01-21 08:31:14.262 [main] INFO logbackCfg.NewDayThread -万里赴戎机,关山度若飞。 2020-01-21 08:31:14.267 [main] ERROR logbackCfg.NewDayThread -朔气传金柝,寒光照铁衣。 2020-01-21 08:31:14.267 [main] DEBUG logbackCfg.NewDayThread -将军百战死,壮士十年归。
使用如下程序进行替换:
package randomaccessfile; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class RndAccessFile { public static void main(String[] args) { RandomAccessFile rndFile = null; try { rndFile = new RandomAccessFile("D:\logs\rndTest.txt", "rw"); String line = null; long lastPoint = 0; while ((line = rndFile.readLine()) != null) { final long point = rndFile.getFilePointer(); // ASCII字符替换 if(line.contains("ERROR")){ String str=line.replace("ERROR", "error"); rndFile.seek(lastPoint); rndFile.writeBytes(str); } // UTF8字符替换 String utf8 = new String(line.getBytes("ISO-8859-1"),"UTF-8"); if(utf8.contains("秦时明月汉时关")){ String str=utf8.replace("秦时明月汉时关", "葡萄美酒夜光杯");// Must be same length rndFile.seek(lastPoint); rndFile.write(str.getBytes("UTF-8")); } lastPoint = point; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { rndFile.close(); } catch (IOException e) { e.printStackTrace(); } } } }
替换结果:
2020-01-21 08:31:08.520 [main] INFO logbackCfg.App -葡萄美酒夜光杯 2020-01-21 08:31:08.521 [main] error logbackCfg.App -万里长征人未还 2020-01-21 08:31:08.521 [main] DEBUG logbackCfg.App -但使龙城飞将在 2020-01-21 08:31:08.521 [main] TRACE logbackCfg.App -不教胡马度阴山 2020-01-21 08:31:10.311 [main] INFO logbackCfg.App2 -九里山前作战场 2020-01-21 08:31:10.317 [main] error logbackCfg.App2 -牧童拾得旧刀枪 2020-01-21 08:31:10.317 [main] DEBUG logbackCfg.App2 -微风吹皱乌江水 2020-01-21 08:31:10.317 [main] TRACE logbackCfg.App2 -恰似虞姬别霸王 2020-01-21 08:31:13.521 [main] INFO logbackCfg.App -葡萄美酒夜光杯 2020-01-21 08:31:13.521 [main] error logbackCfg.App -万里长征人未还 2020-01-21 08:31:13.521 [main] DEBUG logbackCfg.App -但使龙城飞将在 2020-01-21 08:31:13.521 [main] TRACE logbackCfg.App -不教胡马度阴山 2020-01-21 08:31:14.262 [main] INFO logbackCfg.NewDayThread -万里赴戎机,关山度若飞。 2020-01-21 08:31:14.267 [main] error logbackCfg.NewDayThread -朔气传金柝,寒光照铁衣。 2020-01-21 08:31:14.267 [main] DEBUG logbackCfg.NewDayThread -将军百战死,壮士十年归。
参考资料: