本文介紹了用java將GBK工程轉為uft8,分享給大家,具體如下:
windows下的默認編碼為GBK還有gb2312,如何把gbk的java工程轉為utf8的呢,如果直接修改工程編碼,其實里面的java文件中中文是會亂碼的,寫了個批量轉換java工程的程序,消遣一下。
為什么要轉碼?
有些老的項目,或者朋友的項目之前沒注意在windows上不是utf8,而你有需要看注釋或者什么,總不能一個文件一個文件的去改編碼屬性吧。
本程序試用范圍
gbk的代碼,或者gb2312的工程均可以轉換
編碼轉換的思路
本來想做成一個通用的會自動檢測編碼,自動轉換的程序。但是由于判斷編碼類型不準,所以做成了針對GBK的轉換。
- 制定gbk編碼把文件流讀進來,加載到內存,轉為String類型的內容
- 將String內容轉為utf8的String
- 將String內容寫入文件
核心代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
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 ); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
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(); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://geeksblog.cc/trandsferProject.html?utm_source=tuicool&utm_medium=referral