文件存储openFileInput

在Android Studio中,已写入的数据文件存放在data/data/包名/files路径下。若要在Device File Explorer中查看,可能需要同步更新。对于不熟悉文件权限的读者,推荐一篇关于Linux文件权限的博文进行学习。

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

    //写入数据
    public void save(String inputText) {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            /**
             * MODE_PRIVATE 默认模式,其中创建的文件只能由调用应用程序(或共享相同用户ID的所有应用程序)访问
             * 当指定同样文件名的时候,所写入的内容将会覆盖原文件中的内容
             */
            out = openFileOutput("data2.txt", Context.MODE_PRIVATE);
            //通过OutputStreamWriter转换流,把输出字节流转换成输出字符流
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
            writer.flush();        
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

已经写入数据的文件位置在data/data/包名/files目录下,如果要查看文件,如图找到Device File Explorer,我的Android Studio版本是3.2
在这里插入图片描述
倘若没发现files目录,可以同步更新试试
在这里插入图片描述
看不懂文件权限的推荐一篇博文Linux中drwxr-xr-x.的意思和权限

    //读取数据
    public String load() {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = openFileInput("data2.txt");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值