java 大文件 文件字符集转换

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

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值