1. 問題描述:
原始數據是以行為單位的, 每行固定長度931個字節, 漢字占2個字節, 按照字典描述,共有96個字典,只有第32個字典為中文地址, 所以需要單獨處理. 由於項目設計保密,故刪除敏感數據. 供實驗的數據是測試數據.
在處理過程中,按照規定的字典長度截取字符串的時候,發現處理到漢字的時候出錯. 那就需要單獨處理漢字. 比較麻煩. 所以寫了如下簡便方法, 如有更好的解決方案,還請多多交流.
2. 解決方案:
源碼:
package com.dk.rf; import java.io.*; import java.util.ArrayList; import java.util.List; /** * Created by zzy on 17/1/9. */ public class ReadFile { public static void main(String[] args) { String path = "/Users/zzy/Downloads/QQdownload/test-readhanzi.txt"; readFileByLines(path); } /** * 以行為單位讀取文件,常用於讀面向行的格式化文件 */ public static void readFileByLines(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { System.out.println("以行為單位讀取文件內容,一次讀一整行:"); // reader = new BufferedReader(new FileReader(file)); reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK")); String tempString = null; int line = 1; // 一次讀入一行,直到讀入null為文件結束 while ((tempString = reader.readLine()) != null) { handleLines(tempString); char [] chars; chars = tempString.toCharArray(); line++; if (line > 100){ break ; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } /** * 處理一行 * @param line */ public static void handleLines(String line){ // System.out.println(line.length()); // 每一行數據分為96個字段 List strList = new ArrayList(); int start = 0; int end = 0; int [] ss = {42,42,42,8,3,1,1,1,1,1, 6,10,11,11,11,11,11,21,21,21, 4,6,12,4,6,4,3,2,12,6, 8,15,40,3,4,6,10,1,1,5, 2,2,2,2,4,4,11,11,12,12, 12,12,3,3,8,1,8,8,8,8, 8,8,8,8,8,8,8,1,16,8, 8,8,8,8,8,32,2,1,2,14, 4,3,9,12,3,1,8,1,12,15, 21,1,2,1,1,97 }; for (int i = 0; i < ss.length; i++ ){ if (i == 32){ // 單獨處理地址 char[] cc = line.toCharArray(); int ss_32=0 ;// int ff = 0; System.out.println("-------"+start); for (int j = start; j < start+ss[i]; j++) { ss_32++; ff ++; if (!isLetter(cc[j])){ // 如果是漢字 ss_32++; } if (ss_32 == 40){ ss[i] = ff; break; } } } end = start + ss[i]; if(start>=line.length()) return; String temp = line.substring(start, end); start = end; strList.add(temp); System.out.println("ss["+ i+ "]"+ss[i]+"temp="+temp); // TO ,設計業務,需要繼續,春節后交接 } } /** * 判斷一個字符是Ascill字符還是其它字符(如漢,日,韓文字符) * * @param c * @return */ public static boolean isLetter(char c) { int k = 0x80; return (c / k) == 0 ? true : false; } }