android中的文件存储

本文介绍了一个简单的Android应用程序示例,演示如何使用HandFile类通过FileInputStream和FileOutputStream进行文件的读取与写入操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用FileInputStream和FileOutputStream的对象调用方法来创建

将数据写入手机内存

public class HandFile {
    private Context context;

    public HandFile(Context context) {
        this.context = context;
    }

    public void writeFileData(String filename,String message){
        try {
            FileOutputStream fileOutputStream =context.openFileOutput(filename,context.MODE_PRIVATE);
            byte[] bytes=message.getBytes();
            fileOutputStream.write(bytes);
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String readFileData(String fileName){
        String result="";
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = context.openFileInput(fileName);
            int length=fileInputStream.available();
            byte[] bytes=new byte[length];
            fileInputStream.read(bytes);
            result=new String(bytes);
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

}
自己创建 的HandFile类

public class MainActivity extends AppCompatActivity {
    private TextView mtv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String message="emmmm……我就是传说中的数据,嘻嘻嘻。我特么学android好累啊," +
                "可是又有什么办法呢,谁让我大一大二两年太放纵了呢,现在学点东西不至于找不到工作吧," +
                "考研也很累啊,下雪了,我的书还能到吗……";
        HandFile handFile=new HandFile(this);
        handFile.writeFileData("first",message);
        String result=handFile.readFileData("first");

        mtv= (TextView) findViewById(R.id.file);
        mtv.setText(result);

    }
}
将message的内容存入TextView。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值