work hard work smart

专注于Java后端开发。 不断总结,举一反三。
随笔 - 1158, 文章 - 0, 评论 - 153, 阅读 - 187万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Android 文件操作

Posted on   work hard work smart  阅读(227)  评论(0编辑  收藏  举报

Android 文件操作操作时,要赋予相应的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 下面是向文件写文本的代码:

     private final static String PATH = "/sdcard/lin";
private final static String FILENAME = "/test.txt";
 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    writeFile();
}
 
private void writeFile() {
    //判断设备是否存在sdcard
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        try {
            Log.d("File Operation", "start!");
            File path = new File(PATH);
            File file = new File(PATH+FILENAME);
            //如果不存在此路径,则创建此路径
            if (!path.exists()) {
                path.mkdir();
            }
            //如果不存在此文件,则创建此文件
            if (!file.exists()) {
                file.createNewFile();
            }
            //将"text message!"信息写入相应的文件
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file));
            osw.write("text message!");
            osw.close();
            Log.d("File Operation", "success!");
        } catch (Exception e) {
            Log.d("File Operation", "file create error");
        }
         
    }
     
}

 

编辑推荐:
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
阅读排行:
· C# 13 中的新增功能实操
· 万字长文详解Text-to-SQL
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· 卧槽!C 语言宏定义原来可以玩出这些花样?高手必看!
点击右上角即可分享
微信分享提示