資源描述:
《java 文件編碼轉(zhuǎn)換》由會(huì)員上傳分享,免費(fèi)在線(xiàn)閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫(kù)。
1、java文件編碼轉(zhuǎn)換packagecom.folkSeal.util;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.UnsupportedEncodingException;importjava.nio.ByteBuffer;importj
2、ava.nio.channels.FileChannel;importjava.nio.charset.Charset;/**IO工具類(lèi)*/publicclassIOCVUtils{/**源文件編碼*/publicstaticStringsourceEncoding="GBK";/**目標(biāo)編碼*/publicstaticStringtargetEncoding="UTF-8";/***文件內(nèi)容轉(zhuǎn)編碼*@paramsourceFile*@paramtargetFile*@throwsUnsupporte
3、dEncodingException*@throwsFileNotFoundException*@throwsIOException*/publicstaticvoidchangeEncoding(FilesourceFile,FiletargetFile)throwsUnsupportedEncodingException,FileNotFoundException,IOException{FileInputStreamfin=null;FileOutputStreamfout=null;FileC
4、hannelfcin=null;FileChannelfcout=null;if(sourceEncoding==null){IOCVUtils.sourceEncoding=System.getProperty("file.encoding");}try{fin=newFileInputStream(sourceFile);fout=newFileOutputStream(targetFile);fcin=fin.getChannel();fcout=fout.getChannel();ByteBu
5、fferbuffer=ByteBuffer.allocateDirect(1024);while(true){buffer.clear();intr=fcin.read(buffer);if(r==-1){break;}buffer.flip();fcout.write(ByteBuffer.wrap(Charset.forName(sourceEncoding).decode(buffer).toString().getBytes(targetEncoding)));}}finally{if(fin
6、!=null){fin.close();fin=null;}if(fcin!=null){fcin.close();fcin=null;}if(fout!=null){fout.close();fout=null;}if(fcout!=null){fcout.close();fcout=null;}}}/***文件內(nèi)容轉(zhuǎn)編碼*@paramsourceFile*@paramtargetFile*@throwsUnsupportedEncodingException*@throwsFileNotFound
7、Exception*@throwsIOException*/publicstaticvoidchangeEncoding(StringsourceFile,StringtargetFile)throwsUnsupportedEncodingException,FileNotFoundException,IOException{Filefl1=newFile(sourceFile);Filefo1=newFile(targetFile);changeEncoding(fl1,fo1);}/***文件內(nèi)容
8、轉(zhuǎn)編碼*@paramsourceFile*@paramtargetFile*@paramsourceEncoding源文件編碼默認(rèn)源文件的系統(tǒng)存儲(chǔ)編碼System.getProperty("file.encoding");*@paramtargetEncoding目標(biāo)編碼默認(rèn)utf-8*@throwsUnsupportedEncodingException*@throwsFileNotFoundException*@throwsIOException*/