从Android应用程序保存文件

时间:2013-07-18 22:34:57

标签: android file save

我会将文件保存到下载文件夹中。在我的应用程序中,我称之为:

public void export(List<VarA> a) {
    String filename = "text.txt";
    FileOutputStream outputStream;      
    try {
        outputStream = openFileOutput(filename, Context.MODE_APPEND);
        List<String> data = new ArrayList<String>();
        data.add("This is my file.\n\n");
        for (int i=0; i<esami.size(); i++) {
            data.add("\n\nName: "+ a.get(i).getName()+"\n");
        }
        outputStream.write(data.toString().getBytes());
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

有了这个我将我的文件保存到data / data / app / files /,我必须更改为保存到mnt / sdcard / download?谢谢!

1 个答案:

答案 0 :(得分:1)

String externalStoragePath = Environment.getExternalStorageDirectory().toString();
File file = new File(externalStoragePath + "/download/text.txt");
FileOutputStream outputStream;  
try {
    outputStream = new FileOutputStream(file);
    List<String> data = new ArrayList<String>();
    data.add("This is my file.\n\n");
    for (int i=0; i<esami.size(); i++) {
        data.add("\n\nName: "+ a.get(i).getName()+"\n");
    }
    outputStream.write(data.toString().getBytes());
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if(outputStream!=null) outputStream.close();
}

您还需要<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />