我是 Stackoverflow 和编程论坛的新手,所以如果我没有按预期发布我的问题,请原谅我 :)。
我还尝试搜索一个小时的答案,但令人惊讶的是找不到任何有用的东西。
我正在编写代码以使用 inputfilestream 将 windows 文件移动到另一个文件夹。问题是,当在 Windows 中打开文件时(在某些情况下必须如此)打开一个新文件并将其分配给 inputfilestream 失败:
java.io.FileNotFoundException: C:\Users\N\Desktop\source\Doc1.docx (系统找不到指定的文件)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.init> (来源不明)
所以我发现尝试打开文件流时,我必须确保它已关闭。但我找不到通过 Java 代码关闭 windows 文件的方法。所有我能找到的都是java.nio.File,它是虚拟的并且没有关闭方法。那我该怎么做呢?谁能帮我找到这种行动的参考?
我的相关代码:
private void moveFileToFolder(File sourceDir, File destDir, Path prevFileName, String newFileName){
InputStream inStream = null;
OutputStream outStream = null;
byte[] buffer = new byte[1024];
int length;
try{
try{ //wait so windows can close file successfully
//(if it was opened as a new file and then closed automatically) before trying to read from it
wait(1000);
}catch(Exception e ){}
File source =new File(sourceDir.getPath() + "\\" + prevFileName);
File dest =new File(destDir.getPath() + "\\" + newFileName);
inStream = new FileInputStream(source);
outStream = new FileOutputStream(dest);
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
source.delete();
if (DEBUG_MODE){
System.out.println("File was copied successfully!");
}
}catch(IOException e){
e.printStackTrace();
}
}
非常感谢!诺亚