如何在Android上创建文本文件并将数据插入该文件

Mic*_*lle 42 android file

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

Kar*_*thi 105

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

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)

这是代码:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在写入文件之前,还必须检查SD卡是否已挂载且外部存储状态是否可写.

Environment.getExternalStorageState()
Run Code Online (Sandbox Code Playgroud)


hcp*_*cpl 10

检查android文档.事实上它与标准的java io文件处理没什么不同,所以你也可以查看那些文档.

来自android文档的一个例子:

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
Run Code Online (Sandbox Code Playgroud)


Pir*_*hah 5

如果要创建文件并多次写入文件并向其添加数据,请使用以下代码,如果不存在则将创建文件,如果存在则将添加数据。

 SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
        Date now = new Date();
        String fileName = formatter.format(now) + ".txt";//like 2016_01_12.txt


         try
            {
                File root = new File(Environment.getExternalStorageDirectory()+File.separator+"Music_Folder", "Report Files");
                //File root = new File(Environment.getExternalStorageDirectory(), "Notes");
                if (!root.exists()) 
                {
                    root.mkdirs();
                }
                File gpxfile = new File(root, fileName);


                FileWriter writer = new FileWriter(gpxfile,true);
                writer.append(sBody+"\n\n");
                writer.flush();
                writer.close();
                Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
            }
            catch(IOException e)
            {
                 e.printStackTrace();

            }
Run Code Online (Sandbox Code Playgroud)