UF.IMAGEIO
当尝试使用已被释放的资源时,就会报告 UF(使用已释放)问题。UF.IMAGEIO 警告表明尝试在 ImageIO 流已被关闭后使用它。
示例 1
复制
public boolean canDecodeInput(ImageInputStream stream) {
byte[] b = new byte[8];
try {
final long l = stream.length();
if (l > 655335) {
return false;
}
stream.mark();
stream.readFully(b);
stream.reset();
} catch (IOException e) {
return false;
} finally {
try {
stream.close();
} catch (IOException e) {
// do nothing
}
}
// Cast unsigned character constants prior to comparison
return (b[0] == (byte) 'm' && b[1] == (byte) 'y' &&
b[2] == (byte) 'f' && b[3] == (byte) 'o' &&
b[4] == (byte) 'r' && b[5] == (byte) 'm' &&
b[6] == (byte) 'a' && b[7] == (byte) 't');
}
public void decode(Object data) throws IOException {
final ImageInputStream stream = ImageIO.createImageInputStream(data);
if (canDecodeInput(stream)) {
try {
final int[] colors = new int[(int) stream.length()];
for (int i = 0; i < colors.length; i++) {
colors[i] = stream.readInt();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
针对第 48 行的代码段报告 UF.IMAGEIO:在第 31 行关闭了图像输入流 stream 后再次使用它。
示例 2
复制
public boolean canDecodeInput(ImageInputStream stream) {
byte[] b = new byte[8];
try {
final long l = stream.length();
if (l > 655335) {
return false;
}
stream.mark();
stream.readFully(b);
stream.reset();
} catch (IOException e) {
return false;
}
// Cast unsigned character constants prior to comparison
return (b[0] == (byte) 'm' && b[1] == (byte) 'y' &&
b[2] == (byte) 'f' && b[3] == (byte) 'o' &&
b[4] == (byte) 'r' && b[5] == (byte) 'm' &&
b[6] == (byte) 'a' && b[7] == (byte) 't');
}
public void decode(Object data) throws IOException {
final ImageInputStream stream = ImageIO.createImageInputStream(data);
try {
if (canDecodeInput(stream)) {
try {
final int[] colors = new int[(int) stream.length()];
for (int i = 0; i < colors.length; i++) {
colors[i] = stream.readInt();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
stream.close();
}
}
来自之前部分的代码段经过了修复。方法“canDecodeInput”不再关闭流。现在,它通过“decode”方法来关闭,即开启该流的方法。通常,通过最初用来分配资源的相同方法来释放资源是良好的编码做法。