编码格式批转换,将指定编码转换为设置的编码

来源:互联网 发布:分层数据流程图 编辑:程序博客网 时间:2024/05/29 08:32

将指定目录下所有文件转码

package com.dou361;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;public class CopyFolder {public static void main(String[] args) throws IOException {// 源文件路径String src = "D:\\Android\\adt-bundle-windows-x86_64\\workspace\\eluxue_online";String dest = "C:\\Users\\Administrator\\Desktop";copyFolderUTF8toGBK(new File(src), new File(dest));System.out.println("复制完成");}/*** * 复制工程项目文件夹,过滤里面的Java文件,将GBK其转为UTF-8的编码格式 *  * @param src *            原工程项目文件夹的路径 * @param dest *            保存的工程目录路径 * @throws IOException *             复制异常 */public static void copyFolderUTF8toGBK(File filePath, File fileDest)throws IOException {copyFolder("UTF-8","GBK", filePath, fileDest);}/*** * 复制工程项目文件夹,过滤里面的Java文件,将GBK其转为指定的编码格式 *  * @param src *            原工程项目文件夹的路径 * @param dest *            保存的工程目录路径 * @throws IOException *             复制异常 */public static void copyFolderGBKtoUTF8(File filePath, File fileDest)throws IOException {copyFolder("GBK", "UTF-8", filePath, fileDest);}/*** * 复制工程项目文件夹,过滤里面的Java文件,将其转为指定的编码格式 *  * @param srcCoding *            原编码格式(如GBK) * @param desCoding *            转换的编码格式(如UTF-8) * @param src *            原工程项目文件夹的路径 * @param dest *            保存的工程目录路径 * @throws IOException *             复制异常 */public static void copyFolder(String srcCoding, String desCoding, File src,File dest) throws IOException {if (!src.exists()) {return;}/** 当前目录 */String strdest = dest.getAbsolutePath() + File.separator+ src.getName();File fileDestZi = new File(strdest);/** 创建当前目录 */fileDestZi.mkdirs();File[] files = src.listFiles();for (File file : files) {if (file.isDirectory()) {copyFolder(srcCoding, desCoding, file, fileDestZi);} else {if (file.getName().endsWith(".java")|| file.getName().endsWith(".JAVA")) {/** 获取文件编码 */String charset = srcCoding;/** 编码相同,无需转码 */if (charset.equalsIgnoreCase(desCoding)) {return;}/** 复制内容 */FileInputStream is = new FileInputStream(file);FileOutputStream os = new FileOutputStream(fileDestZi.getAbsolutePath() + File.separator+ file.getName());BufferedReader br = new BufferedReader(new InputStreamReader(is, charset));BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, desCoding));while (br.ready()) {bw.append(br.readLine());bw.newLine();}br.close();bw.close();} else {/** 复制内容 */FileInputStream is = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(is);BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileDestZi.getAbsolutePath()+ File.separator + file.getName()));byte[] bys = new byte[8192];int len;while ((len = bis.read(bys)) != -1) {bos.write(bys, 0, len);}bos.close();bis.close();}}}}}


0 0
原创粉丝点击