Android 讀取記憶體檔案返回byte陣列
阿新 • • 發佈:2019-02-02
File file = new File(Environment.getExternalStorageDirectory()+"/w650.jpg");
private byte[] readFile(File file) { // 需要讀取的檔案,引數是檔案的路徑名加檔名 if (file.isFile()) { // 以位元組流方法讀取檔案 FileInputStream fis = null; try { fis = new FileInputStream(file); // 設定一個,每次 裝載資訊的容器 byte[] buffer = new byte[1024]; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // 開始讀取資料 int len = 0;// 每次讀取到的資料的長度 while ((len = fis.read(buffer)) != -1) {// len值為-1時,表示沒有資料了 // append方法往sb物件裡面新增資料 outputStream.write(buffer, 0, len); } // 輸出字串return outputStream.toByteArray(); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("檔案不存在!"); } return null; }