作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
目前我的代码中遇到 FileOutputStream 问题,使用 FileOutputStream 在磁盘中创建文件。创建文件后,无法从其位置打开、删除或移动文件,已经收到错误消息被其他用户锁定当网络服务器停止时,它可以正常工作。我该如何解决这个问题。
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
您正在创建两个 FileOutputStream
实例,并将它们都分配给 out
,但只关闭一个。
删除第二个 out = new FileOutputStream(new File(uploadedFileLocation));
。
此外,您应该考虑使用 try-with-resources block
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try (OutputStream out = new FileOutputStream(new File(uploadedFileLocation))) {
int read = 0;
byte[] bytes = new byte[1024];
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
}
或finally
block 以确保流关闭
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
OutputStream out = null;
try {
out = new FileOutputStream(new File(uploadedFileLocation))
int read = 0;
byte[] bytes = new byte[1024];
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException exp) {
}
}
}
}
参见The try-with-resources Statement了解更多详情
关于Java FileOutputStream 创建文件未解锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30907903/
我是一名优秀的程序员,十分优秀!