How to save parsed text file in internal/external storage in android

泪湿孤枕 提交于 2019-12-01 07:34:11

First thing, your AndroidManifest.xml file is correct. So no need to correct that. Though I would recommend organizing your permissions in one place.

Writing File to Internal Storage

FileOutputStream fOut = openFileOutput("myinternalfile.txt",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);

//---write the contents to the file---
osw.write(strFileData);
osw.flush();
osw.close();

Writing File to External SD Card

//This will get the SD Card directory and create a folder named MyFiles in it.
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/MyFiles");
directory.mkdirs();

//Now create the file in the above directory and write the contents into it
File file = new File(directory, "mysdfile.txt");
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(strFileData);
osw.flush();
osw.close();

Note: If running on an emulator, ensure that you have enabled SD Card support in the AVD properties and allocated it appropriate space.

Replace this lines

File myFile = new File("sdcard/mysdfile.txt");
if(!myFile.exists()){
  myFile.mkdirs();
 }
myFile = new File("sdcard/mysdfile.txt");

with

//Saving the parsed data.........

File myFile = new File(Environment.getExternalStorageDirectory()+"/mysdfile.txt");
myFile.createNewFile();
File myFile = new File("sdcard/mysdfile.txt");

Should be changed to

File myFile = new File("/mnt/sdcard/mysdfile.txt");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!