I'm trying to create a folder on my device and the result isn't as expected.
I do have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in AndroidManifest.xml.
My code:
public void saveOnDevice(){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/hello");
boolean x = true;
if (!myDir.exists()) {
x = myDir.mkdirs();
}
if(x) {
System.out.println("Folder created " + root);
}
else{
System.out.println("Folder not created" + root);
}
}
Result:
Folder not created /storage/emulated/0
Expected:
Folder created /storage/emulated/0
I tried this on my Samsung Galaxy S8. I don't have a SD-Card inserted. I don't have the path /storage/emulated/0 on my device. Why isn't it working and how can I fix this problem?
You do have that folder /storage/emulated/0 on your device. You probably just can't see it due to the layer of abstraction when using Samsungs file browser.
You can verify that by using a more advanced file browser such as FX File Explorer (https://play.google.com/store/apps/details?id=nextapp.fx) and start looking up that path from "System /".
That root string won't help you.
Instead you want to do something like this:
// create folder "myDir" in internal storage as sub directory of /storage/emulated/0
File myDir = new File(Environment.getExternalStorageDirectory(), "myDir");
// create file
File myFile = new File(myDir, "song.mp3");
// get file stream
FileOutputStream fileStream = new FileOutputStream(myFile);
Then you can simply write your songs content to fileStream.
It's a bit confusing that Environment.getExternalStorageDirectory() actually gives you the internal storage location, but it is external to your apps directory which is something like Android/your.apps.packagename/.
Related
I am able to download files ( mp4 videos) in Android using DownloadManager set to a specific path, but when I try to get the file names from the path it outputs a ".lock" file as the name of my files. I want the name of the files I have downloaded:
File[] files = fileDirectoy.listFiles();
This statement (as below) returns null for the files array. The folder does contain four .mp4 videos
The code that I used is listed below.
File fileDirectoy = Environment.getExternalStorageDirectory();
DownloadManager.Request request = new DownloadManager.Request(uriVideo);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(getApplicationContext(), fileDirectoy.toString(), myListOfDocuments.get(i).get("name").toString() + ".mp4");
//todo: Enable this to download videos downloadManager.enqueue(request);
//Lists Files in Local Storage
if(fileDirectoy.exists()) {
File[] files = fileDirectoy.listFiles();
for(File file : files) {
Log.d("MyLog","File name: "+file.getName());
Log.d("MyLog","File path: "+file.getAbsolutePath());
Log.d("MyLog","Size :"+file.getTotalSpace());
}
} else {
Log.d("MyLog", "File directory does not exist");
}
Not sure why this behavior is taking place.
I am trying to write a bitmap to any of the usual internal folders like 'Pictures, Documents, Download' etc. Below is the file creation I am doing
String root = Environment.getRootDirectory().toString();
File myDir = new File(root + File.separator + Environment.DIRECTORY_PICTURES);
String Filename = "pic.png";
File fl = new File(myDir + File.separator + Filename);
FileOutputStream out = new FileOutputStream(fl);
At the last line, it throws an exception which says 'No such File/Directory'.
If I check fl.canWrite(), it says false!, i.e. fl is not writable.
I even tried to give 'Unrestricted Access' in my testing mobile for this App.
What could be the problem?
What kind of additional things I need to do?
Edit: When I toast, myDir is shown as /system/Pictures. When I go to File Manager in phone, under my 'Phone storage', 'Pictures' folder is there. That's a usual folder in Android right ?
you should use
\\...
File myDir = new File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
\\...
then do a check to confirm directory exist and then proceed to write your file.
I am trying to have a local backup of a database of my app in the device storage. I created a backup file/directory, but I want user to restrict from being able to copy/delete the file/directory from the device.
Is it possible to achieve this through code, using a service which I am running?
Method to check if user has permissions to write on external storage or not.
public static boolean canWriteOnExternalStorage() {
// get the state of your external storage
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// if storage is mounted return true
Log.v(“sTag”, “Yes, can write to external storage.”);
return true;
}
return false;
}
and then let’s use this code to actually write to the external storage:
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + “/your-dir-name/”);
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, “My-File-Name.txt”);
FileOutputStream os = outStream = new FileOutputStream(file);
String data = “This is the content of my file”;
os.write(data.getBytes());
os.close();
You need the following permission
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />
Happy coding!!
I'm new to developing android apps. And already overchallenged with my first project. My app should be able to save a list of EditText fields to a text file by clicking a "save"-Button.
But I got no success to write a file to my SD-card.
My code:
(function in MainActivity.java called by the button)
public void saveData(View view){
try{
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/myapp/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, "datei.txt");
FileOutputStream os = new FileOutputStream(file);
String data = "some string";
os.write(data.getBytes());
os.flush();
os.close();
}
catch (IOException e){
Log.e("com.sarbot.FitLogAlpha", "Cant find Data.");
}
}
With Google I found another way:
public void saveData3(View view){
FileWriter fWriter;
File sdCardFile = new File(Environment.getExternalStorageDirectory() + "/datafile.txt");
Log.d("TAG", sdCardFile.getPath()); //<-- check the log to make sure the path is correct.
try{
fWriter = new FileWriter(sdCardFile, true);
fWriter.write("CONTENT CONTENT UND SO");
fWriter.flush();
fWriter.close();
}catch(Exception e){
e.printStackTrace();
}
}
In my manifest.xml I set the permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
And the function from developer guide returns me True -> SD-card is writable.
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
In the res/layout/activity_main.xml are some TextViews and EditText and a save button with android:onClick="saveData" argument. The function is called. The SD-card is writable. And no IO errors. But after pressing the button (without error) there is still no new file on my SD-card. I already tried to create the file manually and just append but nothing changed. I tried some other function with BufferedWriter too .. but no success.
I'm running my Sony Xperia E with USB-Debug mode. Unmount and mounted the SD-card on my PC but cant find the file. Maybe it is only visible for the phone? It doesn't exist? I don't know what to do because I get no errors. I need the content of this file on my computer for calculations.
:EDIT:
The problem was not in the code.. just in the place I looked up. The externalStorage -> sdCard seems to be the internal and the removable sdcard is the -> ext_card.
After this line,
File file = new File(dir, "datei.txt");
Add this code
if ( !file.exists() )
{
file.createNewFile(); // This line will create new blank line.
}
os.flush() is missing in your code. Add this snippet before os.close()
I use the following code to create a folder "mymir" and a file ".nomedia" (in the mymir-folder) on the sdcard of an android unit. However, somehow it fails with the exception that the folder the ".nomedia"-file is to be placed in dosn't exist. Here's the code:
private String EnsureRootDir() throws IOException
{
File sdcard = Environment.getExternalStorageDirectory();
File mymirFolder = new File(sdcard.getAbsolutePath() + "/mymir/");
if(!mymirFolder.exists())
{
File noMedia = new File(mymirFolder.getAbsolutePath() + "/.nomedia");
noMedia.mkdirs();
noMedia.createNewFile();
}
return mymirFolder.getAbsolutePath();
}
I SD really there?
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) == true
If targeting 1.6+, have you declared
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
?
The exact Exception could help.