java獲取inputstream輸入流是什么編碼格式

錯誤筆記:

一開始使用的方法,正常運行沒多久,出現一個情況,GBK文件會導致csv文件的第一行第一列亂碼,百思不得其解,最終發現是因為在源頭,早已使用byte,inputstream。read讀取幾個字節,所以導致后面的亂碼。
錯誤示例如下:
文件:12345.csv,格式為GBK

主鍵,密碼,創建時間,創建人,修改時間,修改人,是否刪除
中文,123456,null,null,null,null,false

錯誤部分代碼:

/**
     * CSV文件編碼
     */
    private static final String ENCODE = "UTF-8";
    /**
     * GBK編碼
     * */
    private static final String ENCODE_GBK = "GBK";
public static List<String> getLines(InputStream fileName) {
        List<String> stringList=null;
        try {
            //判斷文件格式
            byte[] bytes=new byte[3];
            fileName.read(bytes);

            if(bytes[0]==-17&&bytes[1]==-69&&bytes[2]==-65){
                stringList=getLines(fileName, ENCODE);
            }else{
                stringList= getLines(fileName, ENCODE_GBK);
            }
        }catch (Exception e){
            log.error("解析編碼格式異常:"+e.getMessage());
        }finally {
            try {
                if (fileName != null) {
                    fileName.close();
                }
            }catch (IOException e) {
                log.error("解析編碼格式異常Close stream failure :{}", e);
            }
        }
return stringList;
    }
錯誤源頭就在于,byte[] bytes=new byte[3];原本是想這樣去判斷bytes是什么編碼格式,這樣就會導致后面,丟失字節,造成亂碼。后改為如下正確完整代碼。
import lombok.extern.slf4j.Slf4j;
import org.apache.any23.encoding.TikaEncodingDetector;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class CSVFileUtil {
    /**
     * CSV文件編碼
     */
    private static final String ENCODE = "UTF-8";
    /**
     * GBK編碼
     * */
    private static final String ENCODE_GBK = "GBK";
    /**
     * 讀取CSV文件得到List,默認使用UTF-8編碼
     * @param fileName 文件路徑
     * @return
     * 針對編碼格式做處理,謹記關閉流,所以在此處初始化變量list,在獲取行數方法執行完畢后,finally關閉流。
     * 謹記對于流處理,如在調用getLines方法前,采用byte或者其他方法read之后,傳參數fileName,其實已經把流讀取完畢,為空引起報錯。
     */
    public static List<String> getLines(InputStream fileName) {
        List<String> stringList=null;
        ByteArrayOutputStream arraystream=ToolExcelUtils.cloneInputStream(fileName);
        InputStream inputStream=null;
        InputStream stream=new ByteArrayInputStream(arraystream.toByteArray());
        Charset charset= guessCharset(stream);
        try {
            if(charset!=null){
                if(charset.name().equals(ENCODE)){
                    inputStream=new ByteArrayInputStream(arraystream.toByteArray());
                    stringList=getLines(inputStream, ENCODE);
                }else{
                    inputStream=new ByteArrayInputStream(arraystream.toByteArray());
                    stringList= getLines(inputStream, ENCODE_GBK);
                }
            }
        }catch (Exception e){
            log.error("解析編碼格式異常:"+e.getMessage());
        }finally {
            try {
                if (fileName != null) {
                    fileName.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }
                if(stream!=null){
                    stream.close();
                }
            }catch (IOException e) {
                log.error("解析編碼格式異常Close stream failure :{}", e);
            }
        }
return stringList;
    }

    /**
     * 讀取CSV文件得到List
     * @param fileName 文件路徑
     * @param encode 編碼
     * @return
     */
    public static List<String> getLines(InputStream fileName, String encode) {
        List<String> lines = new ArrayList<String>();
        BufferedReader br = null;
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(fileName, encode);
            br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                StringBuilder sb = new StringBuilder();
                sb.append(line);
                boolean readNext = countChar(sb.toString(), '"', 0) % 2 == 1;
                // 如果雙引號是奇數的時候繼續讀取。考慮有換行的是情況
                while (readNext) {
                    line = br.readLine();
                    if (line == null) {
                        return null;
                    }
                    sb.append(line);
                    readNext = countChar(sb.toString(), '"', 0) % 2 == 1;
                }
                lines.add(sb.toString());
                System.out.println(sb.toString());
            }
        } catch (Exception e) {
            log.error("Read CSV file failure :{}", e);
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (IOException e) {
                log.error("Close stream failure :{}", e);
            }
        }
        return lines;
    }

    public static String[] fromCSVLine(String source) {
        return fromCSVLine(source, 0);
    }

    /**
     * 把CSV文件的一行轉換成字符串數組。指定數組長度,不夠長度的部分設置為null
     * @param source
     * @param size
     * @return
     */
    public static String[] fromCSVLine(String source, int size) {
        List list = fromCSVLineToArray(source);
        if (size < list.size()) {
            size = list.size();
        }
        String[] arr = new String[size];
        list.toArray(arr);
        return arr;
    }

    public static List fromCSVLineToArray(String source) {
        if (source == null || source.length() == 0) {
            return new ArrayList();
        }
        int currentPosition = 0;
        int maxPosition = source.length();
        int nextComa = 0;
        List list = new ArrayList();
        while (currentPosition < maxPosition) {
            nextComa = nextComma(source, currentPosition);
            list.add(nextToken(source, currentPosition, nextComa));
            currentPosition = nextComa + 1;
            if (currentPosition == maxPosition) {
                list.add("");
            }
        }
        return list;
    }

    /**
     * 把字符串類型的數組轉換成一個CSV行。(輸出CSV文件的時候用)
     *
     * @param arr
     * @return
     */
    public static String toCSVLine(String[] arr) {
        if (arr == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            String item = addQuote(arr[i]);
            sb.append(item);
            if (arr.length - 1 != i) {
                sb.append(",");
            }
        }
        return sb.toString();
    }

    /**
     * 將list的第一行作為Map的key,下面的列作為Map的value
     * @param list
     * @return
     */
    public static List<Map<String, Object>> parseList(List<String> list) {
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        String firstLine = list.get(0);
        String[] fields = firstLine.split(",");
        for (int i = 1; i < list.size(); i++) {
            String valueLine = list.get(i);
            String[] valueItems = CSVFileUtil.fromCSVLine(valueLine);
            Map<String, Object> map = new HashMap<String, Object>();
            for (int j = 0; j < fields.length; j++) {
                map.put(fields[j], valueItems[j]);
            }
            resultList.add(map);
        }
        return resultList;
    }

    /**
     * 字符串類型的List轉換成一個CSV行。(輸出CSV文件的時候用)
     *
     * @param strArrList
     * @return
     */
    public static String toCSVLine(ArrayList strArrList) {
        if (strArrList == null) {
            return "";
        }
        String[] strArray = new String[strArrList.size()];
        for (int idx = 0; idx < strArrList.size(); idx++) {
            strArray[idx] = (String) strArrList.get(idx);
        }
        return toCSVLine(strArray);
    }

    /**
     * 計算指定字符的個數
     *
     * @param str   文字列
     * @param c     字符
     * @param start 開始位置
     * @return 個數
     */
    private static int countChar(String str, char c, int start) {
        int index = str.indexOf(c, start);
        return index == -1 ? 0 : countChar(str, c, index + 1) + 1;
    }

    /**
     * 查詢下一個逗號的位置。
     *
     * @param source 文字列
     * @param st     檢索開始位置
     * @return 下一個逗號的位置。
     */
    private static int nextComma(String source, int st) {
        int maxPosition = source.length();
        boolean inquote = false;
        while (st < maxPosition) {
            char ch = source.charAt(st);
            if (!inquote && ch == ',') {
                break;
            } else if ('"' == ch) {
                inquote = !inquote;
            }
            st++;
        }
        return st;
    }

    /**
     * 取得下一個字符串
     *
     * @param source
     * @param st
     * @param nextComma
     * @return
     */
    private static String nextToken(String source, int st, int nextComma) {
        StringBuilder strb = new StringBuilder();
        int next = st;
        while (next < nextComma) {
            char ch = source.charAt(next++);
            if (ch == '"') {
                if ((st + 1 < next && next < nextComma) && (source.charAt(next) == '"')) {
                    strb.append(ch);
                    next++;
                }
            } else {
                strb.append(ch);
            }
        }
        return strb.toString();
    }

    /**
     * 在字符串的外側加雙引號。如果該字符串的內部有雙引號的話,把"轉換成""。
     *
     * @param item 字符串
     * @return 處理過的字符串
     */
    private static String addQuote(String item) {
        if (item == null || item.length() == 0) {
            return "\"\"";
        }
        StringBuilder sb = new StringBuilder();
        sb.append('"');
        for (int idx = 0; idx < item.length(); idx++) {
            char ch = item.charAt(idx);
            if ('"' == ch) {
                sb.append("\"\"");
            } else {
                sb.append(ch);
            }
        }
        sb.append('"');
        return sb.toString();
    }
    public static Charset guessCharset(InputStream is)  {
        try {
            return Charset.forName(new TikaEncodingDetector().guessEncoding(is));
        }catch (Exception e){
            log.error("獲取流格式異常:"+e.getMessage());
        }
        return null;
    }
}

測試例子:

File xlsxfile=new File("D:\\測試上傳文件\\csv解析日期失敗文件\\專用文件_20210125163437.csv");
InputStream xlsxinputStream= new FileInputStream(xlsxfile);
        StopWatch watch=new StopWatch();
        watch.start();
        List<Map<String, Object>> dataList= CSVFileUtil.getLines(xlsxinputStream);
        watch.stop();
        System.out.println("執行完畢,共耗時:"+watch.getTotalTimeSeconds()+"秒,數量"+dataList.size());
如上代碼,引入了一個工具包來獲取流的編碼格式:
<dependency>
            <groupId>org.apache.any23</groupId>
            <artifactId>apache-any23-encoding</artifactId>
            <version>2.4</version>
        </dependency>
public static Charset guessCharset(InputStream is)  {
        try {
            return Charset.forName(new TikaEncodingDetector().guessEncoding(is));
        }catch (Exception e){
            log.error("獲取流格式異常:"+e.getMessage());
        }
        return null;
    }
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,837評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,196評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,688評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,654評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,456評論 6 406
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,955評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,044評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,195評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,725評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,608評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,802評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,318評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,048評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,422評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,673評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,424評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,762評論 2 372

推薦閱讀更多精彩內容