I wonder whether you can help me out with this question. I don't understand how I can access e.g. the "Download" folder or some of my own folder.
I want to create some txt-files and have access to it over USB. I didn't find a topic related to my question cause I don't know where exactly I am searching for.
String string = "hello world!";
FileOutputStream fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
Thanks for hints :)
Start by reading the official documentation on file storage options. Remember that external storage doesn't equate to "removable SD-card". It can just as easily be the 32Gb or whatever memory you have on your Nexus device.
Here's an example of how to get the base folder of the files dir (ie the folder that gets deleted when you uninstall the app, as opposed to the cache dir that still exist even after uninstall):
String baseFolder;
// check if external storage is available
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
baseFolder = context.getExternalFilesDir(null).getAbsolutePath()
}
// revert to using internal storage
else {
baseFolder = context.getFilesDir().getAbsolutePath();
}
String string = "hello world!";
File file = new File(basefolder + "test.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();
UPDATE: Since you require the file to be accessible via USB and your PCs file manager instead of DDMS or similar you could use the Environment.getExternalStoragePublicDirectory() and pass Environment.DIRECTORY_DOWNLOADS as argument (note that I'm not sure if there's an equivalent for the internal storage):
String baseFolder;
// check if external storage is available
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
baseFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
// revert to using internal storage (not sure if there's an equivalent to the above)
else {
baseFolder = context.getFilesDir().getAbsolutePath();
}
String string = "hello world!";
File file = new File(basefolder + File.separator + "test.txt");
file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.flush();
fos.close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With