Context:
把目录下的文件内容,全部复制到另一个文件中。
问题:
用简单的 destFile << srcFile 英文没问题,中文会出现乱码
然后srcFile.getText("GBK"),中文奇数结尾会出现乱码
原因:
因为中文系统 默认字符集是GBK,如果读写不制定,就会拿操作系统默认的GBK。但文件保存的是UTF-8,所以转换就会有问题
解决办法:
统一输入与输出的字符集,都用UTF-8
def sourcePath = "app/src/main/java"
//def sourcePath = "app/src/androidTest/java"
def sourceDir = new File(sourcePath)
def destFile = new File('copySource.java')
if (!destFile.exists()) {
destFile.createNewFile();
}
def copySource
copySource = { File srcFile ->
if (srcFile == null || !srcFile.exists()) {
println "File is null or not exits"
return;
}
println "Handle file ${srcFile.name}"
if (srcFile.isDirectory()) {
srcFile.listFiles().each { file ->
copySource(file)
}
} else {
if (srcFile.name.endsWith('.java')) {
println "Start copy ${srcFile.name}"
destFile.append(srcFile.getText("UTF-8"), "UTF-8")
}
}
}
copySource(sourceDir)