Java解決java.io.FileNotFoundException: E:\work\work (拒絕訪問。)
一、問題 在使用FileInputStream或FileOutputStream時會遇到如下問題1和問題2。 問題1:
java.io.FileNotFoundException: .\xxx\xxx.txt (系統找不到指定的路徑。) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(Unknown Source) at java.io.FileOutputStream.<init>(Unknown Source) at com.yaohong.test.InputStreamTest.fileInputStream(InputStreamTest.java:13) at com.yaohong.test.InputStreamTest.main(InputStreamTest.java:27)
問題2:
java.io.FileNotFoundException: .\xx\xx (拒絕訪問。) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(Unknown Source) at java.io.FileOutputStream.<init>(Unknown Source) at com.yaohong.test.InputStreamTest.fileInputStream(InputStreamTest.java:13) at com.yaohong.test.InputStreamTest.main(InputStreamTest.java:27)
二、分析 在進行分析時,我得說清楚什麼時候拋拒絕訪問,什麼時候拋找不到指定路徑。原因是這樣的,在構造一個File物件時,指定的檔案路徑是什麼都可以,就算不存在也能夠構造File物件,但是,現在你要對檔案進行輸入輸出操作,也就是InputStream和OutputStream操作時,如果填寫的路徑不存在,那麼就會報系統找不到指定路徑,如果指定的是目錄時,就會報拒絕訪問異常。看了這個前提之後,在繼續往下讀。
當遇到問題1時,的確是當前所指定的檔案不存在或者目錄不存在。 當遇到第二個問題時,是因為你訪問的是一個檔案目錄,如果這個目錄沒有許可權訪問或者是目錄不存在,就會丟擲問題2的異常。
三、解決辦法 第一個的解決辦法是,先判斷一下當前檔案是否存在,如果存在則略過,如果不存在,在建立,具體做法如下:
//在填寫檔案路徑時,一定要寫上具體的檔名稱(xx.txt),否則會出現拒絕訪問。 File file = new File("./mywork/work.txt"); if(!file.exists()){ //先得到檔案的上級目錄,並建立上級目錄,在建立檔案 file.getParentFile().mkdir(); try { //建立檔案 file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } }
第二個的解決辦法是,在填寫檔案的路徑時一定要具體到檔案,如下:
File file = new File("./mywork/work.txt");
而不能寫成:
File file = new File("./mywork/");
因為這樣你訪問的是一個目錄,因此就拒絕訪問。
四、原始碼(我的demo)
1、檔案輸出流
/** * 檔案輸出流方法 */ public void fileOutputStream() { File file = new File("./mywork/work.txt"); FileOutputStream out = null; try { if (!file.exists()) { // 先得到檔案的上級目錄,並建立上級目錄,在建立檔案 file.getParentFile().mkdir(); file.createNewFile(); }
//建立檔案輸出流 out = new FileOutputStream(file); //將字串轉化為位元組 byte[] byteArr = "FileInputStream Test".getBytes(); out.write(byteArr); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
}
2、檔案輸入流方法
/** * 檔案輸入流 */ public void fileInputStream() { File file = new File("./mywork/work.txt"); FileInputStream in = null; //如果檔案不存在,我們就丟擲異常或者不在繼續執行 //在實際應用中,儘量少用異常,會增加系統的負擔 if (!file.exists()){ throw new FileNotFoundException(); } try { in = new FileInputStream(file); byte bytArr[] = new byte[1024]; int len = in.read(bytArr); System.out.println("Message: " + new String(bytArr, 0, len)); in.close(); } catch (IOException e) { e.printStackTrace(); } }