如何在 Android 上创建文本文件并将数据插入该文件 [英] How to create text file and insert data to that file on Android

查看:31
本文介绍了如何在 Android 上创建文本文件并将数据插入该文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建 file.txt 并在我的代码中包含一些变量内容的文件中插入数据,例如:population [][];在Android上,因此文件资源管理器中我们的包上会有文件夹文件(data/data/ourpackage/files/ourfiles.txt)谢谢

How can I create file.txt and insert data on file with content of some of variable on my code for example : population [][]; on Android, so there will be folder files on our package in file explorer (data/data/ourpackage/files/ourfiles.txt) Thank You

推荐答案

使用此代码,您可以写入 SDCard 中的文本文件.除此之外,您还需要在 Android Manifest 中设置权限.

Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.

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

这是代码:

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

在写入文件之前,您还必须检查您的 SDCard 是否已挂载 &外部存储状态是可写的.

Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.

Environment.getExternalStorageState()

这篇关于如何在 Android 上创建文本文件并将数据插入该文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆