java文件格式转换

给了个例子,把编码格式为GB2312的文件转换成utf-8格式的文件


package com.hikvision.preplan;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class FileEncodeTransfer {
private static String sourceEncoding = "GB2312";
private static String targetEncoding = "UTF-8";



public static void changeEncoding(File sourceFile, File targetFile)
throws UnsupportedEncodingException, FileNotFoundException,
IOException {
FileInputStream fin = null;
FileOutputStream fout = null;
FileChannel fcin = null;
FileChannel fcout = null;
if (sourceEncoding == null) {
FileEncodeTransfer.sourceEncoding = System.getProperty("file.encoding");
}
try {
fin = new FileInputStream(sourceFile);
fout = new FileOutputStream(targetFile);
fcin = fin.getChannel();
fcout = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
while (true) {
buffer.clear();
int r = fcin.read(buffer);
if (r == -1) {
break;
}
buffer.flip();
fcout.write(ByteBuffer.wrap(Charset.forName(sourceEncoding)
.decode(buffer).toString().getBytes(targetEncoding)));
}
} finally {
if (fin != 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;
}
}
}
public static void changeEncoding(String sourceFile, String targetFile) throws UnsupportedEncodingException, FileNotFoundException, IOException{
File fl1 = new File(sourceFile);
File fo1 = new File(targetFile);
changeEncoding(fl1, fo1);
}


public static void changeEncoding(String sourceFile, String targetFile,
String sourceEncoding, String targetEncoding) throws UnsupportedEncodingException, FileNotFoundException, IOException {
FileEncodeTransfer.sourceEncoding = sourceEncoding;
FileEncodeTransfer.targetEncoding = targetEncoding;
changeEncoding(sourceFile, targetFile);
}

public static void main(String[] args){
try {
changeEncoding("D:/bb.html","D:/bbu.html");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值