昨天突然下了個Java項目,把項目導入到eclipse中,發現項目是gbk編碼格式想把項目變為utf-8,但是發現轉換格式比較麻煩就寫了這個代碼,后面改進了下,想到說不定有人也需要就把它寫了出來
代碼如下
代碼比較簡單看懂了自己可以寫一下,可以當做一個關於io流的一個練習
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
/**
* 把gbk編碼的程序變換為用utf-8的格式編碼
*
* 此程序只是為了改變 .java文件的編碼格式如果你想要變換為其他格式只需要改變下面對應的編碼按格式
*
* @author ylg
*/
public class Files {
/**
*
* @param args
* @throws UnsupportedEncodingException
* @throws IOException
*/
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
Scanner scan = new Scanner(System.in);
System.out.println("請輸入需要改變編碼格式的文件位置");
String str = scan.nextLine();
File file = new File(str);
System.out.println("文件的初始編碼");
String bm1 = scan.nextLine();
System.out.println("文件需要轉換成的編碼");
String bm2 = scan.nextLine();
getAllFiles(file, bm1, bm2);
}
/**
*
* @param file 要編譯的文件
* @param bm1 文件的初始編碼
* @param bm2 文件需要轉換成的編碼
* @throws FileNotFoundException 文件找不到
* @throws UnsupportedEncodingException 編碼出錯
* @throws IOException io異常
*/
public static void getAllFiles(File file, String bm1, String bm2) throws FileNotFoundException, UnsupportedEncodingException, IOException {
if (file.isDirectory()) {
File[] test = file.listFiles();
for (File test1 : test) {
//類的名字
String str = test1.getPath();
if (str.endsWith("java") & test1.isFile()) {
String[] s = str.split("\\.");
String filecope = s[0] + "cope." + s[1];
System.out.println(filecope);
File fil = new File(filecope);
//轉格式
InputStreamReader isr = new InputStreamReader(new FileInputStream(test1), bm1);
OutputStreamWriter osr = new OutputStreamWriter(new FileOutputStream(fil), bm2);
int re = -1;
while ((re = isr.read()) != -1) {
osr.write(re);
}
isr.close();
osr.close();
InputStreamReader isrr = new InputStreamReader(new FileInputStream(fil), bm2);
OutputStreamWriter osrw = new OutputStreamWriter(new FileOutputStream(test1), bm2);
int r = -1;
while ((r = isrr.read()) != -1) {
osrw.write(r);
}
isrr.close();
osrw.close();
boolean d = fil.delete();
System.out.println(str + "文件轉換utf-8成功:" + d);
}
getAllFiles(test1, bm1, bm2);
}
}
}
}
寫的不好的地方大家可以說一下共同學習!