前些时候需要把项目中的文本文件都从GBK编码转换为UTF-8编码. 如果要手动的一个个的改, 那可费事了. 反正想学学Groovy, 就用Groovy做的转换脚本吧.
代码如下:
在cfg中定义 输入目录和输出目录
然后递归的遍历目录中的文件, 用GKB编码读进来, 再用UTF-8编码写出去.
其中有一段
byte [] head = [ - 17 , - 69 , - 65 ]
of.newOutputStream() << head
因为UTF-8编码有with Signature和without Signature两种.就是文件开头的EF BB BF
如果你需要without Signature的就把这两句去掉.
代码如下:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->
def cfg
=
[
src : ' e:\\src ' ,
out : ' e:\\out '
];
def dir = new File(cfg.src);
def out_dir = new File(cfg.out);
if ( ! out_dir.exists()) out_dir.mkdirs();
dir.eachFileRecurse{ f ->
println f.path
def out = " ${cfg.out}\\${f.path.substring(cfg.out.length())} "
def of = new File(out)
if (f.isDirectory() && ! of.exists()){
of.mkdirs()
} else {
if ( ! of.exists()){
of.delete();
}
of.createNewFile();
byte [] head = [ - 17 , - 69 , - 65 ]
of.newOutputStream() << head
f.eachLine{ line ->
of.append(line + ' \n ' , ' UTF-8 ' );
}
}
}
src : ' e:\\src ' ,
out : ' e:\\out '
];
def dir = new File(cfg.src);
def out_dir = new File(cfg.out);
if ( ! out_dir.exists()) out_dir.mkdirs();
dir.eachFileRecurse{ f ->
println f.path
def out = " ${cfg.out}\\${f.path.substring(cfg.out.length())} "
def of = new File(out)
if (f.isDirectory() && ! of.exists()){
of.mkdirs()
} else {
if ( ! of.exists()){
of.delete();
}
of.createNewFile();
byte [] head = [ - 17 , - 69 , - 65 ]
of.newOutputStream() << head
f.eachLine{ line ->
of.append(line + ' \n ' , ' UTF-8 ' );
}
}
}
在cfg中定义 输入目录和输出目录
然后递归的遍历目录中的文件, 用GKB编码读进来, 再用UTF-8编码写出去.
其中有一段
byte [] head = [ - 17 , - 69 , - 65 ]
of.newOutputStream() << head
因为UTF-8编码有with Signature和without Signature两种.就是文件开头的EF BB BF
如果你需要without Signature的就把这两句去掉.