介绍
这期内容当中小编将会给大家带来有关利用java如何将GBK转换为uft8,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
具体如下:
windows下的默认编码为GBK还有gb2312,如何把GBK的java工程转为utf8的呢,如果直接修改工程编码,其实里面的java文件中中文是会乱码的,写了个批量转换java工程的程序,消遣一下。
<强>为什么要转码? 强>
有些老的项目,或者朋友的项目之前没注意在windows上不是utf8,而你有需要看注释或者什么,总不能一个文件一个文件的去改编码属性吧。
<强>本程序试用范围强>
GBK的代码,或者gb2312的工程均可以转换
<强>编码转换的思路强>
本来想做成一个通用的会自动检测编码,自动转换的程序。但是由于判断编码类型不准,所以做成了针对GBK的转换。
- <李>
制定GBK编码把文件流读进的来,加载到内存,转为字符串类型的内容
李> <李>将字符串内容转为utf8的字符串
李> <李>将字符串内容写入文件
李>核心代码:
public class TransferProject { public 才能static void  transferFile (String 路径名,intdepth) throwsException { ,,,File dirFile =, new 文件(路径); ,,,if (! isValidFile (dirFile)),返回; ,,,//获取此目录下的所有文件名与目录名 ,,,String [], fileList =, dirFile.list (); ,,,int currentDepth =, depth +, 1; ,,,for (int 小姐:=,0;,小姐:& lt;, fileList.length;,我+ +),{ ,,,,,String String =,文件列表(我); ,,,,,File File =, new 文件(dirFile.getPath(),字符串); ,,,,,String name =, file.getName (); ,,,,,//如果是一个目录,搜索深度深度+ +,输出目录名后,进行递归 ,,,,,if (file.isDirectory ()), { ,,,,,,,//递归 ,,,,,,,transferFile (file.getCanonicalPath (),, currentDepth); ,,,,,},{else ,,,,,,,if (name.contains (“.java"), | |, name.contains (“.properties"), | |, name.contains (“.xml")), { ,,,,,,,,,readAndWrite(文件); ,,,,,,,,,System.out.println(时间+ name “, has converted 用utf8 “); ,,,,,,,} ,,,,,} ,,,} ,,} , private 才能static boolean  isValidFile (File dirFile) throwsIOException { ,,,if (dirFile.exists ()), { ,,,,,System.out.println (“file exist"); ,,,,,return 真实; ,,,} ,,,if (dirFile.isDirectory ()), { ,,,,,if (dirFile.isFile ()), { ,,,,,,,System.out.println (dirFile.getCanonicalFile ()); ,,,,,} ,,,,,return 真实; ,,,} ,,,return 假; ,,} private 才能static void  readAndWrite (File 文件)throwsException { ,,,String content =, FileUtils.readFileByEncode (file.getPath (),“GBK"); ,,,FileUtils.writeByBufferedReader (file.getPath (),, new 字符串(content.getBytes (“UTF-8"),“UTF-8")); ,,} public 才能;static  void main (String [], args) throwsException { ,,,//程序入口,制定src的路径 ,,,String path =,“/用户/mac/下载/unit06_jdbc/src"; ,,,transferFile(路径,,1); ,,} }
public class FileUtils { public 才能static void  writeByBufferedReader (String 路径,String 内容){ ,,,try { ,,,,,File File =, new 文件(路径); ,,,,,file.delete (); ,,,,,if (! file.exists ()), { ,,,,,,,file.createNewFile (); ,,,,,} ,,,,,FileWriter fw =, new FileWriter(文件,,假); ,,,,,BufferedWriter bw =, new BufferedWriter (fw); ,,,,,bw.write(内容); ,,,,,bw.flush (); ,,,,,bw.close (); ,,,},catch (IOException e), { ,,,,,e.printStackTrace (); ,,,} ,,} public 才能;staticStringreadFileByEncode (String 路径,String chatSet) throwsException { null null null null null null null null null null null null null利用java如何将GBK转换为uft8