最近整理以前写的代码,发现以前的代码有的是用GBK编码,有的是utf-8编码,整理在一起就会出现中文乱码。而一个一个的整理又比较的麻烦,于是就写了一个转换文件编码的方法,顺便熟悉一下对java I/O流的操作。
package com.platform.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.List;
public class FileUtils {
/**
* @Title: copyFile
* @Description: 拷贝一个文件到另外一个路径
* @param sourcePath 文件源路径
* @param toPath 文件复制之后的路径
* @return void
* @throws
*
* @author ydd
* @date 2015-10 -16
*
*/
public static void copyFile(String sourcePath,String toPath) throws IOException{
File sourceFile = new File(sourcePath);
File toFile = new File(toPath);
if(sourceFile.isDirectory() || !sourceFile.exists()){
return ;
}
if(toFile.isDirectory()){
return;
}
if(!toFile.exists()){
toFile.createNewFile();
}
FileInputStream fIn = new FileInputStream(sourceFile);
FileOutputStream fOut = new FileOutputStream(toFile);
byte[] bt = new byte[1024];
int count ;
while((count = fIn.read(bt)) > 0 ){
fOut.write(bt, 0, count);
}
fIn.close();
fOut.close();
}
/**
* 修改文件的编码
*
* @param file 文件路径(是文件夹则修改该文件夹下所有文件编码)
* @param fromCharset 原编码
* @param destCharset 目标编码
* @return int 修改的文件的个数
*
* @author ydd
* @date 2015-10-15
*
*/
public static int modifyFileCharset(File file,String fromCharset,String destCharset,FilenameFilter filter) throws IOException{
if(!Charset.isSupported(fromCharset) ){
throw new UnsupportedCharsetException(fromCharset);
}
if(!Charset.isSupported(destCharset)){
throw new UnsupportedCharsetException(destCharset);
}
int count = 0;
if(file.isDirectory()){
File[] fileArr = null;
if(filter == null){
fileArr = file.listFiles();
}else{
fileArr = file.listFiles(filter);
}
count = fileArr.length;
for (int i = 0; i < fileArr.length; i++) {
File temp = fileArr[i];
convertFileCharset(temp, fromCharset, destCharset);
}
}else{
convertFileCharset(file, fromCharset, destCharset);
count = 1;
}
return count;
}
/**
*
* 转换单个文件的编码
*
* @param file 文件
* @param fromCharset 转换前编码
* @param destCharset 转换后编码
* @return void
*
* @author ydd
* @date 2015-10-15
*
*/
public static void convertFileCharset(File file,String fromCharset,String destCharset) throws IOException{
String oldFileName = file.getPath() + ".old";
File oldFile = new File(oldFileName);
if(!oldFile.exists()){
oldFile.createNewFile();
}
//将原文件拷贝一份到相同的目录下,并在文件名后加.old
copyFile(file.getPath(), oldFileName);
//以原编码方式读取该文件
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(oldFileName),
fromCharset));
//用新的编码方式向文件中重新写入文件内容
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file.getPath()),
destCharset));
int ch = 0;
while ((ch = br.read()) != -1) {
bw.write(ch);
}
bw.flush();
br.close();
bw.close();
}
}