標籤:拼接
注意:
第一步要先添加許可權:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
步驟:
檔案流
1、寫:
a)建立檔案輸出資料流(PATH)
b)將內容寫入檔案輸出資料流(str.getBytes())
bb)關閉流
2、讀:
a)建立檔案輸入資料流
b)建立位元組數組緩衝(ByteArrayBufferarrayBuffer = new ByteArrayBuffer(1000);)——>為了後面分段讀取時拼接資料
c)建立位元組數組buffer(1024)(建立變數len=0)
d)迴圈讀入——while(-1!=(len=fis.read(buffer)){arrayBuffer.append(buffer, 0, len) }
e)通過建立String的形式將位元組數群組轉換成字串(new String(arrayBuffer.toByteArray()))
f)將內容顯示在文字框中
ff)關閉流
物件流程
1、寫:
a)建立對象
b)建立檔案輸出資料流(PATH)
c)建立對象輸出資料流(ObjectOutputStream,將檔案輸出資料流嵌套在裡面)
d)將對象寫入對象輸出資料流(oos.writeObject(person);)
dd)關閉最外層流(物件流程)
2、讀:
a)建立檔案輸入資料流
b)建立對象輸入資料流
c)將讀到的Object對象強轉成所需對象(Personperson = (Person)ois.readObject();)
d)在文字框中顯示對象的各項內容
dd)關閉最外層流(物件流程)
代碼實現(檔案流):
1、往sdcard中寫入資料
FileOutputStreamfos = null;
try{
fos= new FileOutputStream(PATH);
Stringstr = writeToSdcard.getText().toString();
//將字串打散寫入流中
fos.write(str.getBytes());
}catch (FileNotFoundException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(fos!=null){
try{
//如果path有問題,會跳到finally中,而fos此時為null,會發生null 指標異常
fos.close();
}catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2、從sdcard中讀取資料
FileInputStreamfis = null;
//1000表示的是預留空間
ByteArrayBufferarrayBuffer = new ByteArrayBuffer(1000);
try{
fis= new FileInputStream(PATH);
byte[]buffer = new byte[1024];
intlen = 0;
while(-1!=(len=fis.read(buffer))){
//拼接
arrayBuffer.append(buffer,0, len);
}
//通過建立字串的形式將arrayBuffer轉換成位元組數組
StringreadBuffer = new String(arrayBuffer.toByteArray());
writeToSdcard.setText(readBuffer);
}catch (FileNotFoundException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(fis!=null){
try{
fis.close();
}catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();