gpt4 book ai didi

Java - 解析分隔文件并查找列数据类型

转载 作者:行者123 更新时间:2023-11-29 05:01:41 25 4
gpt4 key购买 nike

是否可以解析分隔文件并查找列数据类型?例如

分隔文件:

Email,FirstName,DOB,Age,CreateDate
test@test1.com,Test User1,20/01/2001,24,23/02/2015 14:06:45
test@test2.com,Test User2,14/02/2001,24,23/02/2015 14:06:45
test@test3.com,Test User3,15/01/2001,24,23/02/2015 14:06:45
test@test4.com,Test User4,23/05/2001,24,23/02/2015 14:06:45

输出:

Email datatype: email
FirstName datatype: Text
DOB datatype: date
Age datatype: int
CreateDate datatype: Timestamp

这样做的目的是读取分隔文件并动态构建表创建查询并将数据插入该表。

我尝试使用 apache validator ,我相信我们需要解析完整的文件以确定每一列的数据类型。

编辑:我试过的代码:

CSVReader csvReader = new CSVReader(new FileReader(fileName),',');
String[] row = null;
int[] colLength=(int[]) null;
int colCount = 0;
String[] colDataType = null;
String[] colHeaders = null;

String[] header = csvReader.readNext();
if (header != null) {
colCount = header.length;
}

colLength = new int[colCount];
colDataType = new String[colCount];
colHeaders = new String[colCount];

for (int i=0;i<colCount;i++){
colHeaders[i]=header[i];
}

int templength=0;
String tempType = null;
IntegerValidator intValidator = new IntegerValidator();
DateValidator dateValidator = new DateValidator();
TimeValidator timeValidator = new TimeValidator();

while((row = csvReader.readNext()) != null) {
for(int i=0;i<colCount;i++) {

templength = row[i].length();

colLength[i] = templength > colLength[i] ? templength : colLength[i];

if(colHeaders[i].equalsIgnoreCase("email")){
logger.info("Col "+i+" is Email");
} else if(intValidator.isValid(row[i])){
tempType="Integer";
logger.info("Col "+i+" is Integer");
} else if(timeValidator.isValid(row[i])){
tempType="Time";
logger.info("Col "+i+" is Time");
} else if(dateValidator.isValid(row[i])){
tempType="Date";
logger.info("Col "+i+" is Date");
} else {
tempType="Text";
logger.info("Col "+i+" is Text");
}

logger.info(row[i].length()+"");
}

不确定这是否是最好的方法,任何指向正确方向的指示都会有所帮助

最佳答案

如果您想自己编写而不是使用第三方库,那么最简单的机制可能是为每种数据类型定义一个正则表达式,然后检查是否所有字段都满足它。下面是一些示例代码,可帮助您入门(使用 Java 8)。

public enum DataType {
DATETIME("dd/dd/dddd dd:dd:dd"),
DATE("dd/dd/dddd",
EMAIL("\\w+@\\w+"),
TEXT(".*");

private final Predicate<String> tester;
DateType(String regexp) {
tester = Pattern.compile(regexp).asPredicate();
}

public static Optional<DataType> getTypeOfField(String[] fieldValues) {
return Arrays.stream(values())
.filter(dt -> Arrays.stream(fieldValues).allMatch(dt.tester)
.findFirst();
}
}

请注意,这取决于枚举值的顺序(例如,在日期之前测试日期时间)。

关于Java - 解析分隔文件并查找列数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31930439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com