一、問題
在使用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();
}
}
如有錯誤,還望指正,謝謝合作。