最近需要比较两个CLOB字段的内容是否相同,得用Java代码实现。 实验了几种方案之后,觉得下面这个比较好一些。
过程如下:
private boolean isEqualCLOB(CLOB sourceCLOB, CLOB targetCLOB) {
boolean retVal = true;
try {
if ((null != sourceCLOB) && (null != targetCLOB)) {
// both not null, should compare.
if (sourceCLOB.length() != targetCLOB.length()) {
// length diff, diff.
retVal = false;
} else {
// length same, should compare the content.
InputStream inStreamSource = sourceCLOB.getAsciiStream();
InputStream inStreamTarget = targetCLOB.getAsciiStream();
retVal = cmpTwoStreams(inStreamSource, inStreamTarget);
inStreamSource.close();
inStreamTarget.close();
} // end compare the length.
} else if ((null == sourceCLOB) && (null == targetCLOB)) {
// both null, equal.
retVal = true;
} else {
// only one is null. diff.
retVal = false;
}
} catch (Exception e) {
// do as you like.
;
}
return retVal;
}
private boolean cmpTwoStreams(InputStream streamSource, InputStream streamTarget) throws IOException {
boolean retVal = true;
byte s = (byte)0;
byte t = (byte)0;
// As we compare the streams only the two CLOB has same length.
while(( s = (byte)streamSource.read()) != -1) {
t = (byte)streamTarget.read();
if (s != t) {
retVal = false;
break;
}
} // end loop of source stream.
return retVal;
}
以上代码,已经测试。
如果有其他好的思路,希望可以交流一下。目的是快速而且占用空间少。