我正在尝试在以 ISO-8859-1 编码的文件中查找和替换一些特殊字符,然后将结果写入以 UTF-8 编码的新文件:
package inv
class MigrationScript {
static main(args) {
new MigrationScript().doStuff();
}
void doStuff() {
def dumpfile = "path to input file";
def newfileP = "path to output file"
def file = new File(dumpfile)
def newfile = new File(newfileP)
def x = [
"þ":"ş",
"ý":"ı",
"Þ":"Ş",
"ð":"ğ",
"Ý":"İ",
"Ð":"Ğ"
]
def r = file.newReader("ISO-8859-1")
def w = newfile.newWriter("UTF-8")
r.eachLine{
line ->
x.each {
key, value ->
if(line.find(key)) println "found a special char!"
line = line.replaceAll(key, value);
}
w << line + System.lineSeparator();
}
w.close()
}
}
我的输入文件内容是:
"þ": "ý": "Þ":" "ð":" "Ý":" "Ð":"
问题是我的代码永远找不到指定的字符。groovy 脚本文件本身以 UTF-8 编码。我猜这可能是问题的原因,但是我不能在 ISO-8859-1 中对其进行编码,因为那时我不能在其中写“Ş”“Ğ”等。