通過讀取文件頭部判斷是否爲CSV格式文件
通過讀取CSV文件頭,判斷文件是是否屬於CSV文件類型,一般而言僅僅只是通過文件後綴來判斷該文件所屬的類型,這樣是不合理的,只要更改一下文件後綴就無法識別這個文件到底是不是正確的文件格式,把可執行的文件後綴改爲.CSV如果是通過判斷文件後綴來識別文件類型,這樣肯定是行不通的,因爲exe的文件格式肯定不是CSV的格式,如果提前判斷出這個文件頭的這樣就能定位這個文件是不是我們所需要的文件類型,避免對錯誤的文件進行解析。同樣也可以在某種程度上保護服務器的安全。
/*
* System Abbrev :
* system Name :
* Component No :
* Component Name:
* File name :Util.java
* Author :Qiuzhenping
* Date :2014-11-30
* Description : <description>
*/
/* Updation record 1:
* Updation date : 2014-11-30
* Updator : Qiuzhenping
* Trace No: <Trace No>
* Updation No: <Updation No>
* Updation Content: <List all contents of updation and all methods updated.>
*/
package com.qiuzhping.util;
import java.io.FileInputStream;
/**
* <Description functions in a word>
* 通過讀取CSV文件頭,判斷文件是是否屬於CSV文件類型,一般而言僅僅只是通過文件後綴來判斷該文件所屬的類型,
* 這樣是不合理的,只要更改一下文件後綴就無法識別這個文件到底是不是正確的文件格式,把可執行的文件後綴改爲.CSV
* 如果是通過判斷文件後綴來識別文件類型,這樣肯定是行不通的,因爲exe的文件格式肯定不是CSV的格式,如果提前判斷
* 出這個文件頭的這樣就能定位這個文件是不是我們所需要的文件類型,避免對錯誤的文件進行解析。同樣也可以在某種程度上
* 保護服務器的安全。
* <Detail description>
*
* @author Qiuzhenping
* @version [Version NO, 2014-11-30]
* @see [Related classes/methods]
* @since [product/module version]
*/
public class Util {
/** <Description functions in a word>
* Bytes to Hex String
* 將字節數組轉換成16進制字符串
* <Detail description>
* @author Qiuzhenping
* @param src
* @return [Parameters description]
* @return String [Return type description]
* @exception throws [Exception] [Exception description]
* @see [Related classes#Related methods#Related properties]
*/
public static String bytes2HexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
System.out.println(" bytes2HexString = "+stringBuilder.toString().toUpperCase());
return stringBuilder.toString().toUpperCase();
}
/** <Description functions in a word>
* Judge this FileInputStream is csv file
* 判斷該文件流頭部是否包含有指定的信息,從而確認該文件是不是正確的文件類型
* <Detail description>
* @author Qiuzhenping
* @param is
* @return [Parameters description]
* @return boolean [Return type description]
* @exception throws [Exception] [Exception description]
* @see [Related classes#Related methods#Related properties]
*/
public static boolean judgeIsCSV(FileInputStream is){
try {
byte[] b = new byte[4];
is.read(b, 0, b.length);
return bytes2HexString(b).contains("5B75726C");//CSV文件的頭部的前4個字節
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws Exception {
String src = "C:/dataTemp/Url使用.csv";
FileInputStream is = new FileInputStream(src);
System.out.println(judgeIsCSV(is));
src = "C:/dataTemp/Url使用.csv";
is = new FileInputStream(src);
System.out.println(judgeIsCSV(is));
}
}
轉載請註明:http://blog.csdn.net/qiuzhping/article/details/41626295