今天,講講如何把程式的byte[]儲存到手機,并且作為檔案可以讀取。
package com.example.edittextresearch;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
// 假設這是從伺服器上擷取的資料,或者其他的什麼地方擷取到的。
byte[] bytes = "hello world".getBytes();
// 根據byte數組生成檔案,儲存到手機上
createFileWithByte(bytes);
// 彈出資訊提示
Toast.makeText(MainActivity.this, "生成檔案成功!", Toast.LENGTH_LONG).show();
}
private String fileName;// 檔案命名
private void initData() {
// TODO Auto-generated method stub
fileName = "byte_to_file.doc";
}
/**
* 根據byte數組生成檔案
*
* @param bytes
* 生成檔案用到的byte數組
*/
private void createFileWithByte(byte[] bytes) {
// TODO Auto-generated method stub
/**
* 建立File對象,其中包含檔案所在的目錄以及檔案的命名
*/
File file = new File(Environment.getExternalStorageDirectory(),
fileName);
// 建立FileOutputStream對象
FileOutputStream outputStream = null;
// 建立BufferedOutputStream對象
BufferedOutputStream bufferedOutputStream = null;
try {
// 如果檔案存在則删除
if (file.exists()) {
file.delete();
}
// 在檔案系統中根據路徑建立一個新的空檔案
file.createNewFile();
// 擷取FileOutputStream對象
outputStream = new FileOutputStream(file);
// 擷取BufferedOutputStream對象
bufferedOutputStream = new BufferedOutputStream(outputStream);
// 往檔案所在的緩沖輸出流中寫byte資料
bufferedOutputStream.write(bytes);
// 刷出緩沖輸出流,該步很關鍵,要是不執行flush()方法,那麼檔案的内容是空的。
bufferedOutputStream.flush();
} catch (Exception e) {
// 列印異常資訊
e.printStackTrace();
} finally {
// 關閉建立的流對象
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
}
我在代碼中都加了注釋,大家看起來也很簡單。大概講講:
- 首先需要擷取byte類型數組資料,這裡我是用的假設的資料,實際中大家發送網絡請求擷取即可;
- 資料拿到後就可以将其寫到檔案緩沖輸出流中,然後調用flush()方法刷出流對象,這樣檔案裡面就有内容了。
> 檔案存到手機上的圖檔如下所示:
其實就是把byte[]通過輸入流寫入到手機,我之前也寫過檔案複制的部落格,和這個功能是類似的。
android 将byte[]儲存到手機就講完了。
就這麼簡單。