这是一个场景,我尝试上传一个文件,上传后,我尝试从新目录(我刚刚写入的目录)访问该文件,但收到错误消息:
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 分钟后,我就可以访问该文件了。有办法解决这个错误吗?
最佳答案
您没有关闭该文件。添加
outputStream.close();
循环之后。
编辑并在关闭其他任何内容之前先执行此操作。你真的应该在这里使用 try-with-resources 。如果您在关闭任何内容时遇到任何异常,则其他关闭将不会发生。
关于java - JAVA中使用HttpServletRequest上传后文件被锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24304125/