这是场景,我尝试上传文件,在我上传文件后,我尝试从新目录(我刚写入)中访问该文件,但收到了错误消息:
打开此文档时出错。该文件已经打开或 在另一个应用程序中使用。
以下是我的编码。
try{
conn = this.getConnection();
String getIP = "SELECT IP FROM TABLE WHERE ID='3'";
ps = conn.prepareStatement(getIP);
rs = ps.executeQuery();
Part file = request.getPart("upload");
String fileName = extractFileName(request.getPart("upload"));
String basePath = "//"+ipAdd+"/ns/"+fileName;
File outputFilePath = new File(basePath + fileName);
inputStream = file.getInputStream();
outputStream = new FileOutputStream(outputFilePath);
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}catch(Exception ex){
ex.printStackTrace();
throw ex;
}finally{
if(!conn.isClosed())conn.close();
if(!ps.isClosed())ps.close();
if(!rs.isClosed())rs.close();
inputStream.close();
outputStream.close();
}
是否因为我在启动上传功能后打开文件太快了?我确实知道在1/2分钟之后,我能够访问该文件。无论如何要解决这个错误吗?
答案 0 :(得分:2)
您没有关闭该文件。添加
outputStream.close();
循环后。
编辑并在关闭其他任何内容之前先执行此操作。你应该在这里使用try-with-resources。如果你得到任何关闭任何异常的事情,那么另一个关闭将不会发生。
答案 1 :(得分:1)
在上面的代码中,如果在关闭JDBC Connection时发生异常,则不会关闭其他JDBC对象或Streams。最后一个块在此时退出。
从Java 7开始,关闭Streams和JDBC对象(Connections,Statements,ResultSets等)可以在一个合适的异常处理框架中完成并且很容易,因为它们都实现了一个公共接口AutoCloseable
因此,您可以编写单个close()
方法并处理内部异常:
public void close(AutoCloseable closeable) {
try {
closeable.close();
} catch (Exception e) {
//Just log the exception. there's not much else you can do, and it probably doesn't
//matter. Don't re-throw!
}
}
因此,在关闭JDBC对象时,可以在finally块中执行此操作:
close(conn);
close(ps);
close(rs);
close(inputStream);
close(outputStream);
现在,如果在关闭任何对象时发生异常,则会处理它,并且以下对象仍然关闭。