python實現JAVA原始碼從ANSI到UTF-8的批量轉換方法

來源:互聯網
上載者:User
本文執行個體講述了python實現JAVA原始碼從ANSI到UTF-8的批量轉換方法。分享給大家供大家參考。具體如下:

喜歡用eclipse的大神們,可能一不小心代碼就變成ANSI碼了,需要轉換成utf-8嘛,一個檔案一個檔案的在Notepad2或者notepad++裡面轉換嗎?不,這裡有批量轉換的程式,python實現,需要的拿去用吧。

ansi2utf8.py:

#-*- coding: utf-8 -*-import codecsimport osimport shutilimport reimport chardetdef convert_encoding(filename, target_encoding): # Backup the origin file. shutil.copyfile(filename, filename + '.bak') # convert file from the source encoding to target encoding content = codecs.open(filename, 'r').read() source_encoding = chardet.detect(content)['encoding'] print source_encoding, filename content = content.decode(source_encoding) #.encode(source_encoding) codecs.open(filename, 'w', encoding=target_encoding).write(content)def main(): for root, dirs, files in os.walk(os.getcwd()):  for f in files:   if f.lower().endswith('.java'):    filename = os.path.join(root, f)    try:     convert_encoding(filename, 'utf-8')    except Exception, e:     print filenamedef 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 sourceif __name__ == '__main__': # process_bak_files(action='clear') main()

把程式拷貝到java源檔案所在目錄下運行就好了。

希望本文所述對大家的Python程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.