試圖創建並寫入到一個文件,但我得到一個FileNotFoundException
每一次,這裏是我使用的方法:FileOutputStream中:FileNotFoundException異常當試圖實例
public void saveFileAsPRN(Context context){
byte[] dataFile = getPrintableFileData();
String filename = "TestPrn.prn";
// instantiate a file object using the path
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
Log.e(TAG, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
//determine if the media is mounted with read & write access
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.e(TAG, "media mounted"); //good
}else{
Log.e(TAG, "media NOT mounted"); //bad
}
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
// determine if the file exists, create it if it does not
if(!file.exists()){
try {
Log.e(TAG, "File does not exist, creating..");
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Log.e(TAG, "File Exists");
}
//this makes the blank file visible in the file browser
MediaScannerConnection.scanFile(context, new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + filename}, null, null);
//create output stream - send data; saving to file
OutputStream out = null;
try {
FileOutputStream fos = null;
fos = new FileOutputStream(file); // <---- CRASHES HERE; FileNotFoundException
out = new BufferedOutputStream(fos);
out.write(dataFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
一個FileNotFoundException
是以下行上調:
fos = new FileOutputStream(file); // <---- CRASHES HERE;
目錄存在,在目標目錄中創建一個空白文件(通過在PC上瀏覽目標文件夾可見)。
調用方法canWrite()
對File
對象返回true - 我有寫權限。
清單包含:android.permission.WRITE_EXTERNAL_STORAGE
「
所以我的想法,我看到幾個人有類似的問題,但我不能找到一個答案
什麼http://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile ()返回?另外,不會'mkdirs()'將文件創建爲目錄? –
檢查讀者是否能夠讀取它,並嘗試使用PrintWriter將數據寫入文件,它可以直接採用File對象。 –