gpt4 book ai didi

Java FileOutputStream 创建文件未解锁

转载 作者:行者123 更新时间:2023-12-01 22:16:20 25 4
gpt4 key购买 nike

目前我的代码中遇到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com