java 大文件 文件字符集转换
最近需要从oracle数据库倒数据到pg 数据库中。 由于某表记录数超大,导出的sql文件超过1G,编辑器打都打不开。通过打开文件后,再转换不可行,网上的文件转换,是直接读到内存再转换。直接报错。
所以只能边读边转码输出。
直接上代码:
package test.com.file;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.charset.Charset;
import java.nio.file.Files;
import org.apache.commons.io.Charsets;
public class GbkToUtf8 {
public static void writeLine(final String line, final OutputStream output,
final Charset charset) throws IOException {
if (line == null) {
return;
}
String lineEnding = System.lineSeparator();
final Charset cs = Charsets.toCharset(charset);
final byte[] eolBytes = lineEnding.getBytes(cs);
if (line != null) {
Channels.newChannel(output).write(Charsets.toCharset(charset).encode(line));
}
output.write(eolBytes);
}
public static void main(String[] args) throws IOException {
// GBK编码格式源码路径
String srcDirPath = "C:\\cust\\pg\\table.sql";
// 转为UTF-8编码格式源码路径
String utf8DirPath = "C:\\cust\\pg\\table_utf.sql";
// 使用GBK读取数据,然后用UTF-8写入数据
File a = new File(srcDirPath);
BufferedReader br = Files.newBufferedReader(a.toPath(), Charsets.toCharset("GBK"));
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(utf8DirPath), false));
String line ="";
while(true) {
line =br.readLine();
if (line == null) {
break;
}
writeLine(line, out, Charsets.toCharset("UTF-8"));
}
out.close();
br.close();
}
}