批量修改java文件编码(GBK->UTF-8),带备份和恢复功能

非常适合转换老项目,或是从网上下载了GBK项目的源码
代码是网上找的,结合了一下:

#-*- coding: utf-8 -*-

import codecs
import os
import shutil
import re
import sys

def convert( filename, in_enc = "GBK", out_enc="UTF-8" ):
    shutil.copyfile(filename, filename + '.bak')

    # read the file
    content = open( filename ).read()
    # convert the concent
    try:
        new_content = content.decode( in_enc ).encode( out_enc )
        #write to file
        open( filename, 'w' ).write( new_content )
    except:
        print " error... "

def explore( dir ):
    for root, dirs, files in os.walk( dir ):
        for file in files:
            if file.lower().endswith('.java'):
                path = os.path.join( root, file )
                print "convert " + path,
                convert( path )
                print " done"

def process_bak_files(action='restore'):
    for root, dirs, files in os.walk(os.getcwd()):
        for f in files:
            if f.lower().endswith('.java.bak'):
                source = os.path.join(root, f)
                target = os.path.join(root, re.sub('\.java\.bak$', '.java', f, flags=re.IGNORECASE))
                try:
                    if action == 'restore':
                        shutil.move(source, target)
                    elif action == 'clear':
                        os.remove(source)
                except Exception, e:
                    print source

def main():
    if len( sys.argv ) > 1 :
        path = sys.argv[1]
        if os.path.isfile( path ):
            convert( path )
        elif os.path.isdir( path ):
            explore( path )

if __name__ == "__main__":
    #process_bak_files(action='clear')
    main() 

用法

python encode.py [path]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值