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();
}

}

}

你可能感兴趣的:(java)