王安石的资料,三级片名大全,单于夜遁逃的上一句
本文介绍了用java将gbk工程转为uft8,分享给大家,具体如下:
windows下的默认编码为gbk还有gb2312,如何把gbk的java工程转为utf8的呢,如果直接修改工程编码,其实里面的java文件中中文是会乱码的,写了个批量转换java工程的程序,消遣一下。
为什么要转码?
有些老的项目,或者朋友的项目之前没注意在windows上不是utf8,而你有需要看注释或者什么,总不能一个文件一个文件的去改编码属性吧。
本程序试用范围
gbk的代码,或者gb2312的工程均可以转换
编码转换的思路
本来想做成一个通用的会自动检测编码,自动转换的程序。但是由于判断编码类型不准,所以做成了针对gbk的转换。
核心代码:
public class transferproject{ public static void transferfile(string pathname,intdepth)throwsexception{ file dirfile = new file(pathname); if (!isvalidfile(dirfile)) return; //获取此目录下的所有文件名与目录名 string[] filelist = dirfile.list(); int currentdepth = depth + 1; for (int i = 0; i < filelist.length; i++) { string string = filelist[i]; file file = new file(dirfile.getpath(), string); string name = file.getname(); //如果是一个目录,搜索深度depth++,输出目录名后,进行递归 if (file.isdirectory()) { //递归 transferfile(file.getcanonicalpath(), currentdepth); } else { if (name.contains(".java") || name.contains(".properties") || name.contains(".xml")) { readandwrite(file); system.out.println(name + " has converted to utf8 "); } } } } private static boolean isvalidfile(file dirfile)throwsioexception{ if (dirfile.exists()) { system.out.println("file exist"); return true; } if (dirfile.isdirectory()) { if (dirfile.isfile()) { system.out.println(dirfile.getcanonicalfile()); } return true; } return false; } private static void readandwrite(file file)throwsexception{ string content = fileutils.readfilebyencode(file.getpath(), "gbk"); fileutils.writebybufferedreader(file.getpath(), new string(content.getbytes("utf-8"), "utf-8")); } public static void main(string[] args)throwsexception{ //程序入口,制定src的path string path = "/users/mac/downloads/unit06_jdbc/src"; transferfile(path, 1); } }
public class fileutils{ public static void writebybufferedreader(string path, string content){ try { file file = new file(path); file.delete(); if (!file.exists()) { file.createnewfile(); } filewriter fw = new filewriter(file, false); bufferedwriter bw = new bufferedwriter(fw); bw.write(content); bw.flush(); bw.close(); } catch (ioexception e) { e.printstacktrace(); } } public staticstringreadfilebyencode(string path, string chatset)throwsexception{ inputstream input = new fileinputstream(path); inputstreamreader in = new inputstreamreader(input, chatset); bufferedreader reader = new bufferedreader(in); stringbuffer sb = new stringbuffer(); string line = reader.readline(); while (line != null) { sb.append(line); sb.append("\r\n"); line = reader.readline(); } return sb.tostring(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论