私は Stackoverflow と一般的にプログラミング フォーラムを初めて使用するので、期待どおりに質問を投稿していない場合はご容赦ください :)。
私も 1 時間答えを探してみましたが、驚くべきことに役立つものは見つかりませんでした。
inputfilestreamを使用してWindowsファイルを別のフォルダーに移動するコードを書いています。問題は、ファイルがウィンドウで開かれている場合 (場合によってはそうである必要があります)、新しいファイルを開いて入力ファイルストリームに割り当てると失敗することです。
java.io.FileNotFoundException: C:\Users\N\Desktop\source\Doc1.docx (指定されたファイルが見つかりません)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.init> (出典不明)
そのため、ファイル ストリームを開こうとすると、それが閉じていることを確認する必要があることがわかりました。しかし、Java コードを使用して Windows ファイルを閉じる方法が見つかりません。私が見つけたのは、仮想的で close メソッドを持たない 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();
}
}
どうもありがとうございました!いや