2013-04-27 195 views
1

我是新來的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

回答

1

如果打開一個文件,您將無法通過Java關閉它,因爲要關閉它,您必須在Java代碼中打開該文件。

您可以做的是創建一個列表並添加所有失敗的文件,然後在處理結束時再次嘗試處理這些文件。

如果仍然失敗,用戶可能會使用它,所以提示用戶幫助或將其記錄到日誌文件以便用戶可以獲取有關文件未處理的信息是很有趣的。

1

開關閉和使用Java刪除窗口的文件...

final File file=new File("E:\\features.xlsx"); 

    //open file 
    if(file.exists()) 
     Runtime.getRuntime().exec("cmd /c start E:\\"+file.getName()); 

    //close and delete a open file 
     Runtime.getRuntime().exec(
      "cmd /c taskkill /f /im excel.exe"); //put "winword.exe" for ms word file 

    new Thread(new Runnable() { 
     @Override 
     public void run() { 

      try { 
        Thread.currentThread().sleep(2000); 
        file.delete();  

       } catch (InterruptedException e) { 

        e.printStackTrace(); 
       } 
     } 
    }).start();