我是新來的Stackoverflow和一般編程論壇,所以請原諒我,如果我沒有發佈我的問題,如預期:)。使用Java打開或關閉打開的Windows文件
我也嘗試搜索一個小時的答案,並出乎意料地找不到任何有用的東西。
我正在編寫一個代碼,通過使用inputfilestream將Windows文件移動到另一個文件夾。問題是,當在Windows打開文件(並且它在某些情況下)打開一個新文件並將其分配給輸入文件流失敗時:
java.io.FileNotFoundException:C:\ Users \ N \桌面\源\ Doc1.docx(系統找不到指定的文件)
在java.io.FileInputStream.open(本機方法)
在java.io.FileInputStream.init>(來源不明)
所以我想到,試圖打開一個文件流,我必須確保它關閉。 但我找不到通過Java代碼關閉Windows文件的方式。 所有我能找到的都被認爲是java.nio.File,它是虛擬的並且沒有close方法。我該怎麼做? 任何人都可以幫我找到這樣的行動的參考?
我的相關代碼段:
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();
}
}
非常感謝您! Noa