問題描述:
使用FileOutputStream,根據文檔上看,new FileOutputStream(path),如果path路徑下的文件不存在,則自動創建新的文件。
但是在使用過程中,
path = Environment.getExternalStorageDirectory().getPath() + "/document/mine/www/te.text";
此時new一個FileOutputStream,會報“File not found”的異常。
問題分析:
修改path路徑,
path = Environment.getExternalStorageDirectory().getPath() + "/document/te.text";
此時再new新的outputstream對象,可正常編譯。
導致前面提到的異常的原因是,文件目錄層級過深。
解決方案:
自己創建不存在的目錄路徑。
在目錄層級大於2時(如“/document/mine/te.text"),mkdirs()方法執行時會返回false。
此處使用拼接的方法,將目錄分段進行創建(如將path分為"/document/mine"和”/www/text"),這樣便可以避免以上問題,實例代碼如下
copyAssetsToSd(context, Environment.getExternalStorageDirectory().getPath() + File.separator + "document", "mine" + File.separator + "cordova.js"); private static void copySingleAssetToSd(Context context, String sdPath, String assetPath) { InputStream inputStream = null; OutputStream outputStream = null; try { File dirFile = new File(sdPath); if (!dirFile.exists()) { dirFile.mkdirs(); // 第一段 } File file = new File(sdPath + File.separator + assetPath); if (!file.getParentFile().exists()) { // 分兩次mkdirs,是為了避免目錄層級過高導致目錄創建失敗的情況 file.getParentFile().mkdirs(); } if (!file.exists()) { file.createNewFile(); } outputStream = new FileOutputStream(file); // 創建實例 inputStream = context.getAssets().open(assetPath); byte[] buffer = new byte[1024]; int length = inputStream.read(buffer); while (length > 0) { outputStream.write(buffer, 0, length); length = inputStream.read(buffer); } outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != inputStream) { inputStream.close(); } if (null != outputStream) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }