該方法是通過讀取文件所在地址,start是讀取的起始行數默認1,由於bufferReader在readL:ine()讀取第一行數據的時候會出現解析""空字符串錯誤。所以導致在程序中出現這種錯誤——兩個在從肉眼上進行比較兩個相同的空串,第一個空串返回false,然後用String lenth() 方法返回1,此時表明導入時讀取文件的空字符串不是真正意義上的空字符,導入文件是csv格式 ,需用文本打開,在讀取本地文件的時候對其進行了轉碼,判斷位於行的第一個字符是否等於65279 ,如果相等從第二個字符截取即可。
File file = new File(path);
public static List<Map<Integer, String>> read(File file, int start)throws OperateSystemException{
if (!file.getName().toUpperCase().endsWith(".CSV")){
return null;
}
BufferedReader reader = null;
InputStreamReader fReader = null;
try {
fReader = new InputStreamReader(new FileInputStream(file),"UTF-8");
List<Map<Integer, String>> list = new ArrayList<>();
reader = new BufferedReader(fReader);
int n = 0;
start = start < 1 ? 1: start;
String line;
String[] temp;
Map<Integer, String> map ;
while ((line = reader.readLine()) != null) {
if (++n < start){
continue;
}
if (StringUtil.isEmpty(line)) {
continue;
}
temp = readLine(line);
if (temp == null){
continue;
}
map= new HashMap<>();
for (int i = 0; i < temp.length; i++) {
if(temp[i].trim().length()>0){
char c = temp[i].trim().charAt(0);
if (c == 65279) {
temp[i] =temp[i].substring(1);
}
}
map.put(i+1, temp[i]);
}
list.add(map);
}
return list;
}catch (FileNotFoundException e){
e.printStackTrace();
ThrowUtil.error(OperateSystemErrorCode.MODULES_CSVUTILS_UPLOAD__FILE_NOT_FOUND);
}
catch (Exception e) {
e.printStackTrace();
ThrowUtil.error(OperateSystemErrorCode.MODULES_CSVUTILS_UPLOAD__IO_EXCEPTION);
return null;
} finally {
try {
if (reader != null) {
reader.close();
reader = null;
}
} catch (IOException e2) {
e2.printStackTrace();
ThrowUtil.error(OperateSystemErrorCode.MODULES_CSVUTILS_UPLOAD__IO_EXCEPTION);
}
}
return null;
}