I want to save a simple .txt
file in Android and later I want to copy this file from the device to a PC where the device is mounted as a MTP-Device.
I own two Android Devices:
- Nexus 4, Stock Android 5.0.1
- Nexus 7 2012, CyanogenMod 12, Android 5.0.2
To make sure that it's not a Nexus device bug I tried a Wiko phone from a friend.
I use this code to save the file to the Downloads folder on the external storage. This is recommended on the developer page.
private void saveData()
{
String fileName = "test.txt";
String writeString = "Hello World";
File filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File saveFile = new File(filePath, fileName);
saveFile.setReadable(true);
try
{
boolean result = saveFile.createNewFile();
if(result == true)
{
Log.i(TAG, "File successfully created");
}
else
{
Log.i(TAG, "Error. File not created");
}
BufferedWriter writer = new BufferedWriter(new FileWriter(saveFile));
writer.write(writeString);
writer.close();
}
catch(Exception e)
{
Log.e(TAG,e.toString());
}
}
I use the following permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
When I use MTP to connect to the device I get an empty download folder but when I access the folder through a File Browser in Android (in my case it's ES File Browser) I can see the file and the content. So I think creating the file and writing to it works.
When creating the file I receive the right Log: "File successfully created."
You need to add the file to the
MediaStore
: (quite a lot of code...)