android File保存数据
将数据直接以文件的形式保存在设备中,通过Context.openFileInput()方法获得标准的JAVA文件输入流(FileInputStream),通过Context.openFileOutput()方法获得标准的JAVA文件输出流(FileOutputStream)
写数据到file文件中
findViewById(R.id.file).setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
try {
//可写入的方式创建或打开huangbiao.txt文件
//该文件的路径是/data/data/包名/files/huangbiao.txt
FileOutputStream fos = openFileOutput("huangbiao.txt",Context.MODE_APPEND);
//将字符串写入到文件中
fos.write("huangbiao".getBytes());
//关闭数据流
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});读取数据的方法
findViewById(R.id.read_file).setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
FileInputStream fis;
try {
//打开文件并得到InputStream对象
fis = openFileInput("huangbiao.txt");
//available()返回估算需要的空间长度
byte[] buffer = new byte[fis.available()];
//把数据流的内容写入buffer中
fis.read(buffer);
String aaa = new String(buffer);
System.out.println(aaa);
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}); 相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gyunwh 2020-11-02