在JAVA中使用HttpServletRequest上载后锁定servlets文件
下面是一个场景,我尝试上载一个文件,上载后,我尝试从新目录(我刚刚写入)访问该文件,但收到错误消息:
There was an error opening this document. The file is already open or in use by another application.
下面是我的代码
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分钟后,我就可以访问该文件了。有没有办法解决这个错误
# 1 楼答案
你不能关闭文件。加上
在循环之后
编辑并在关闭任何其他内容之前先进行编辑。你真的应该在这里使用try with资源。如果关闭任何东西时出现异常,则不会发生其他关闭
# 2 楼答案
在上面的代码中,如果在关闭JDBC连接时发生异常,那么其他JDBC对象或流都不会关闭。最后一个街区在那一点出口
由于Java 7,关闭流和JDBC对象(连接、语句、结果集等)可以在适当的异常处理框架中轻松完成,因为它们都实现了一个公共接口
AutoCloseable
因此,您可以编写一个
close()
方法并在内部处理异常:因此,在关闭JDBC对象时,可以在finally块中执行以下操作:
现在,如果在关闭任何对象时发生异常,则会对其进行处理,并且仍然关闭以下对象