UF.IN
当尝试使用已被释放的资源时,就会报告 UF(使用已释放)问题。UF.IN 警告表明尝试在输入流已被关闭后使用它。
示例 1
复制
public boolean checkMeta(InputStream stream) {
byte[] b = new byte[8];
try {
final long l = stream.available();
if (l < 8) {
return false;
}
stream.read(b);
} 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 printOut(final URL url, final PrintStream ps) throws IOException {
final InputStream stream = url.openStream();
if (checkMeta(stream)) {
try {
ps.println("content:");
byte[] b = new byte[1024];
int i;
while ((i = stream.read(b)) > 0) {
ps.print(new String(b, 0, i));
}
ps.println();
} catch (IOException e) {
e.printStackTrace();
}
}
}
针对第 50 行的代码段报告 UF.IN:在第 30 行关闭了输入流 stream 后再次使用它。
示例 2
复制
public boolean checkMeta(InputStream stream) {
byte[] b = new byte[8];
try {
final long l = stream.available();
if (l < 8) {
return false;
}
stream.read(b);
} 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 printOut(final URL url, final PrintStream ps) throws IOException {
final InputStream stream = url.openStream();
try {
if (checkMeta(stream)) {
try {
ps.println("content:");
byte[] b = new byte[1024];
int i;
while ((i = stream.read(b)) > 0) {
ps.print(new String(b, 0, i));
}
ps.println();
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
stream.close();
} catch (IOException e) {
// do nothing
}
}
}
来自之前部分的代码段经过了修复。方法“checkMeta”不再关闭流。现在,它通过“printOut”方法来关闭,即开启该流的方法。通常,通过最初用来分配资源的相同方法来释放资源是良好的编码做法。