您的位置:首页 > 移动开发 > Android开发

android 40 Io编程

2015-10-18 17:01 387 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: