1.需求
a.经常遇到把windows系统的某个文件或项目拷贝到Linux系统后打开全是乱码,反之亦然。
b.这种情况是由于各个平台的字符编码不同导致的,需要转换。
c.java提供了很多字符集之间的转换的支持。
2.实现思路
a.查询java支持的所有字符集
SortedMap<String, Charset> charsetMap = Charset.availableCharsets();
for (String alias :charsetMap.keySet()) {
System.out.println("java支持的字符集:"+charsetMap.get(alias));
}
b.遍历文件夹下的所有文件
Files.walkFileTree(Paths.get(PATH),new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes basicFileAttributes) throws IOException {
if(file.toString().endsWith(".java") && !file.toString().endsWith("R.java")){
System.out.println("java文件:"+file);
try {
handleFileAndSaveNewFile(file,SRC_CHARSET,DEST_CHARSET);
} catch (Exception e) {
e.printStackTrace();
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes basicFileAttributes) throws IOException {
return FileVisitResult.CONTINUE;
}
});
c.知道原来的字符编码格式和需要转换成的字符编码格式
d.使用java依次对各个文件进行字符编码转换
/**
* 转换文件编码格式(覆盖源文件)
* @param path 源文件路径
* @param srcCharset 源文件编码时的字符集
* @param destCharset 转换后文件的字符集
* @throws Exception io异常
*/
private static void handleFileAndSaveNewFile(Path path, String srcCharset, String destCharset) throws Exception{
//读取源文件
File file = new File(path.toString());
FileInputStream fileInputStream = new FileInputStream(file);
FileChannel inChannel = fileInputStream.getChannel();
MappedByteBuffer mappedByteBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
//解码
Charset decCharset = Charset.forName(srcCharset);
CharsetDecoder decoder = decCharset.newDecoder();
CharBuffer charBuffer = decoder.decode(mappedByteBuffer);
//编码
Charset encCharset = Charset.forName(destCharset);
CharsetEncoder encoder = encCharset.newEncoder();
ByteBuffer encodeByte = encoder.encode(charBuffer);
//替换保存
FileChannel outChannel = new FileOutputStream(path.toString()).getChannel();
outChannel.write(encodeByte);
}
源码:https://github.com/qidashi/format_conversion.git
重要提示:写项目之前一定记得先把工程格式设置为UTF-8,这样就不必转来转去了!!!