昨天忽然下了個Java項目,把項目導入到eclipse中,發現項目是gbk編碼格式想把項目變爲utf-8,可是發現轉換格式比較麻煩就寫了這個代碼,後面改進了下,想到說不定有人也須要就把它寫了出來
代碼以下
代碼比較簡單看懂了本身能夠寫一下,能夠當作一個關於io流的一個練習java
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); } } } }
寫的很差的地方你們能夠說一下共同窗習!eclipse