我对 Java 相当陌生,并且对下面的代码有疑问。下面的 doAggregate 方法是从 csv 文件中读取数据列。我希望能够检查 fields[i] 的值以获取特殊字符和非转义引号,并在附加它们之前将它们从值中删除。代码 as is 错误如下所述:java.lang.Double 不能转换为 java.lang.String。所以听起来并不是所有类型的字段都会转换为字符串值。有没有一种测试字符串是否为字符串的好方法?或者有没有更好的方法来解决这个问题?
public String doAggregate(Object[] fields) {
if (ObjectUtils.isEmpty(fields)) {
return "";
}
if (fields.length == 1) {
return "\"" + ObjectUtils.nullSafeToString(fields[0]) + "\"";
}
String tmp_field_value;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fields.length; i++) {
if (i > 0) {
sb.append(getDelimiter());
}
sb.append("\"");
//start new code
tmp_field_value = (String) fields[i];
//error on line below
sb.append(getCleanUTF8String(tmp_field_value));
//end new code
//start old code
//sb.append(fields[i]);
//end old code
sb.append("\"");
}
return sb.toString();
}
public String getCleanUTF8String(String dirtyString){
String cleanString = "";
try {
byte[] cleanBytes = dirtyString.getBytes("UTF-8");
cleanString = new String(cleanBytes, "UTF-8");
cleanString = cleanString.replace("\"", "\\\"");
cleanString = cleanString.replace("'", "\\'");
} catch (UnsupportedEncodingException uee){
System.out.println("*******ERROR********: Unable to remove non UTF-8 characters in string: |" + dirtyString + "| -- Java Error Message:" + uee.getMessage());
//TODO - may need to revisit this next line, some additional character checks may need to take place if the character set exclusion fails.
cleanString = dirtyString;
}
return cleanString;
}