1. 程式人生 > >java 檔案轉碼(gb2315,gbk,utf-8)csv,excel

java 檔案轉碼(gb2315,gbk,utf-8)csv,excel

最近做資料處理,需要將爬取的資料入庫,但是演算法提供的資料編碼格式和資料庫總是有出入,導致匯入的資料亂碼,所以寫一個轉碼程式,將檔案編碼轉為和資料庫一致。

package com.bjk.transcode;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * @author baojikui (
[email protected]
) * @date 2018/12/17 */ public class Transcode { public static void main(String args[]) { try { //需要轉碼的檔案 InputStream is = new FileInputStream("/tmp/filename_old"); InputStreamReader isr = new InputStreamReader(is, "gb2312"); //轉碼後的檔案 OutputStream os = new FileOutputStream("/tmp/filename_new"); OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8"); char[] chr = new char[1024]; int length; while ((length = isr.read(chr, 0, 1024)) > 0) { System.out.println(new String(chr, 0, length)); osw.write(chr, 0, length); osw.flush(); } isr.close(); osw.close(); } catch (Exception e) { } } }

以上。