天天看點

Android檔案存儲詳解

【讀寫外部存儲的幾個前提】/ File dirFile = getExternalFilesDir(Environment.DIRECTORY_MOVIES); File file = new File(dirFile.getAbsolutePath() + File.separator + "abc.mp4"); if (file.exists()) { file.delete(); } else { boolean newFile = file.createNewFile(); if (!newFile) { Toast.makeText(MainActivity.this, "建立目标檔案失敗!", Toast.LENGTH_SHORT).show(); return; } }

//向目标檔案寫入資料 fos = new FileOutputStream(file); //1、将輸入流轉化為bytes baos = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len = -1; while ((len = is.read(bytes)) != -1) { baos.write(bytes, 0, len);//将小水桶中的内容倒入大水缸 } byte[] videoBytes = baos.toByteArray();

//2、向目标檔案的fos灌裝bytes fos.write(videoBytes); fos.flush();

} catch (Exception e) { e.printStackTrace(); Toast.makeText(MainActivity.this, "異常:" + e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); }

if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } }

if (baos != null) { try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }

【檔案和流的核心API】 ================================================== ·Environment.getExternalStorageDirectory()——拿到外部存儲的根目錄 ·File.separator——相容版的路徑分隔符,即:"/"或"\",根據作業系統的不同而不同 ---------------------------------------- ·File file = new File(path);——根據路徑建立檔案對象(隻是一個虛拟的File對象,不是檔案實體) ·file.getAbsolutePath()——拿到檔案的絕對路徑 ·boolean success = file.delete();——删除檔案,傳回值true代表删除成功 ·boolean exists = file.exists();——判斷檔案是否存在 ·boolean isDirectory = file.isDirectory();——判斷檔案是否為檔案夾,true=是檔案夾,否則為檔案 ·boolean success = file.createNewFile();——建立檔案(位址自然為file所對應的位址) ·boolean success = dirFile.mkdirs();——建立檔案夾(如路徑很長則實際建立的是一連串的路徑) ---------------------------------------- ·FileInputStream fis = new FileInputStream(file);——拿到檔案的輸入流(以讀入其内容) ·FileOutputStream fos = new FileOutputStream(file, true);——拿到檔案的輸出流(以向其中寫出資料),true=以追加方式寫入,false=以覆寫方式寫入 ·int length = inputStream.read(buffer);——将輸入流中的資料倒入位元組數組buffer中,并傳回buffer的長度,如果長度為-1則表示沒有倒入任何内容(即inputStream已經倒光) ·fos.write(bytes);——向檔案輸出流中寫出資料 ·fis.close();——用完之後關閉檔案輸入流 ·fos.close();——關閉檔案輸出流 ---------------------------------------- ·ByteArrayOutputStream baos = new ByteArrayOutputStream();——建立位元組數組輸出流(以向其中寫入byte[]) ·baos.write(bytes, 0, len);——将緩沖區(小水桶)中的内容倒入位元組數組輸出流(大水缸) ·byte[] bytes = baos.toByteArray();——将位元組數組輸出流轉化為位元組數組 ---------------------------------------- ·Bitmap bitmap = BitmapFactory.decodeFile(filePath);——根據指定路徑的圖檔解碼為Bitmap對象 ·Bitmap bitmap = BitmapFactory.decodeStream(inputStream);——将輸入流解碼為Bitmap對象 ·Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);——将圖檔資源解碼為Bitmap對象 ·boolean success = bitmap.compress(format, 100, fos);——将bitmap以format定義的格式、100的品質,寫入檔案輸出流fos對應的檔案中 ---------------------------------------- ·byte[] buffer = new byte[1024];——建立大小為1024位元組的位元組數組(作為讀寫緩沖區) ·byte[] bytes = str.getBytes();——拿到字元串的位元組數組