使用sonarqube检查代码时报错
Use try-with-resources or close this “FileInputStream” in a “finally” clause.
原始代码是这样的,当时是个阻断的bug
private static void copyFile(String copyFile, String newFile) throws Exception {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(copyFile);
fos = new FileOutputStream(newFile, true);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
if (fis != null) {
fis.close();
}
}
}
三种种解决方案
1.finally里close的时候用try{}catch{}包起来就好了
private static void copyFile(String copyFile, String newFile) throws Exception {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(copyFile);
fos = new FileOutputStream(newFile, true);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.类实现AutoCloseable方法也可以,直接不用写finally就可以
public class AutoCloseableDemo {
public static void main(String[] args) {
try (AutoCloseableObjecct app = new AutoCloseableObjecct()) {
System.out.println("--执行main方法--");
} catch (Exception e) {
System.out.println("--exception--");
} finally {
System.out.println("--finally--");
}
}
//自己定义类 并实现AutoCloseable
public static class AutoCloseableObjecct implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("--close--");
}
}
@Test
public void demo2() {
//JDK1.7之前,释放资源方式
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//1.7之后,只要实现了AutoCloseable接口
try (FileInputStream fileInputStream2 = new FileInputStream("")) {
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.直接用try包起来,java8之后try包起来的会自动关闭流
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("file.txt"))) {
// Write to the ObjectOutputStream here
} catch (IOException e) {
e.printStackTrace();
}