Android 存储文件数据与读出文件数据
package gongzibai.co.cc;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.http.util.EncodingUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Sample_4_1 extends Activity {
public static final String ENCODING = "UTF-8"; // 常量,
代表编码格式
String fileName = "test1.txt";// 文件的名称
TextView tv;
EditText editText1,editText2;
Button mButton;
// TextView对象引用
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);// 设置当前屏幕
// 创建文件并写入数据
// 获得从文件读入的数据
tv = (TextView) findViewById(R.id.tv);// 根据id获
取屏幕中TextView对象的引用
// 设置TextView的内容
editText1 = (EditText) findViewById
(R.id.editText1);
editText2 = (EditText) findViewById
(R.id.editText2);
mButton = (Button) findViewById(R.id.button1);
Button mButton2 = (Button) findViewById
(R.id.button2);
mButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method
stub
writeFileData(fileName,
editText1.getText().toString());
editText1.setText("");
}
});
mButton2.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method
stub
String result = readFileData
(fileName);
tv.setText(result);
editText2.setText(result);
}
});
}
// 方法:向指定文件中写入指定的数据
public void writeFileData(String fileName, String
message) {
try {
FileOutputStream fout = openFileOutput
(fileName, MODE_APPEND);// 获得FileOutputStream对象
byte[] bytes = message.getBytes();// 将要
写入的字符串转换为byte数组
fout.write(bytes);// 将byte数组写入文件
fout.close();// 关闭FileOutputStream对象
} catch (Exception e) {
e.printStackTrace();// 捕获异常并打印
}
}
// 方法:打开指定文件,读取其数据,返回字符串对象
public String readFileData(String fileName) {
String result = "";
try {
FileInputStream fin = openFileInput
(fileName);// 获得FileInputStream对象
int length = fin.available();// 获取文件
长度
byte[] buffer = new byte[length];// 创建
byte数组用于读入数据
fin.read(buffer);// 将文件内容读入到byte
数组中
result = EncodingUtils.getString(buffer,
ENCODING);// 将byte数组转换成指定格式的字符串
fin.close(); // 关闭文件输入流
} catch (Exception e) {
e.printStackTrace();// 捕获异常并打印
}
return result;// 返回读到的数据字符串
}
}
更多相关文章
- android上文件上传至tomcat服务器源码
- Android 下载服务器上的文件
- android webview file标签点击弹出选择文件或拍照菜单
- android 从assets和res中读取文件
- Android Bluetooth 文件接收路径修改方法
- Android文件图片上传的详细讲解(三)---模式回调类
- android XML文件序列化
- Android Studio(十二):打包多个发布渠道的apk文件
- [置顶] Android——4.2.2 文件系统目录分析