This article describes a Python-based batch conversion method that implements Java source code from ANSI to UTF-8. Share to everyone for your reference. Specific as follows:
Like with eclipse of the great gods, may accidentally code becomes ANSI code, need to convert to Utf-8, a file of a file in the Notepad2 or notepad++ inside conversion? No, there are batch conversion programs, Python implementation, need to take to use it.
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.O Pen (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 (). Endswit H ('. 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.remo ve (source) except Exception, e:print sourceif __name__ = = ' __main__ ': # process_bak_files (action= ' Clear ') main ()
It's good to copy the program to the directory where the Java source files are located.
Hopefully this article will help you with Python programming.