windows上写的项目放到Linux上出现一堆乱码

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,这样就不必转来转去了!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值