標籤:
Io編程:記憶卡和sd卡。字串存入記憶卡然後讀出來。
activity:
package com.sxt.day06_06;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity { EditText met;//文字框 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); setListener(); } private void setListener() { setSaveDataClickListener(); setReadDataClickListener(); } private void setReadDataClickListener() { findViewById(R.id.btnReadData).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FileInputStream in =null; try { in= openFileInput("file.dat"); byte[] data=new byte[1024]; int len = in.read(data);//返回實際讀取的位元組數 String text=new String(data, 0, len, "utf-8"); Toast.makeText(MainActivity.this, text, 3000).show(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(in!=null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }); } private void setSaveDataClickListener() { findViewById(R.id.btnSaveData).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FileOutputStream out = null; try { out=openFileOutput("file.dat", MODE_PRIVATE); String text=met.getText().toString(); byte[] data=text.getBytes("utf-8");//FileOutputStream時data要轉換為位元組數組 out.write(data); out.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(out!=null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }); } private void initView() { met=(EditText) findViewById(R.id.et); }}
頁面
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/et" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="哈羅,張飛!"/> <Button android:id="@+id/btnSaveData" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="儲存資料" /> <Button android:id="@+id/btnReadData" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="讀取資料" /> </LinearLayout>
android 40 Io編程