Try this code:
public void writeToFile(String fileName, String body)
{
FileOutputStream fos = null;
try {
final File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/folderName/" );
if (!dir.exists())
{
if(!dir.mkdirs()){
Log.e("ALERT","could not create the directories");
}
}
final File myFile = new File(dir, fileName + ".txt");
if (!myFile.exists())
{
myFile.createNewFile();
}
fos = new FileOutputStream(myFile);
fos.write(body.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Also, remember to include the external storage permission in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and on android 6.0 to ask for permission for WRITE_EXTERNAL_STORAGE
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…