I have a section of code that is supposed to check if an mp3 file is stored in the SD card on the MediaStore.Audio.Media content provider
the problem is that no matter the situation. Either if the file with the pathname stored in variable "audioFilename" exists on the SD card or not. it always returns "this file does not exist" as the result. Despite the fact that the variable audioFilename has the String path name stored in it "/mnt/sdCard/Music/Jungle.mp3", and this MP3 file is actually on the SD card. Easy to prove with a Toast message and a check of the SD card contents.
I probably have an error in the use of File or Environment classes. Can anyone see a problem in the code shown here?
// toast message to prove that the audioFilename is not null,
// message displayed is the string, "File name: /mnt/sdCard/Music/Jungle.mp3"
Toast.makeText(Editor.this, "File name: " + audioFilename,
Toast.LENGTH_LONG).show();
// the code below always returns "this file does not exist"
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "audioFilename");
if(myFile.exists()){
Toast.makeText(Editor.this, "<<<< this file exists, it is: "+audioFilename+" >>>>",
Toast.LENGTH_LONG).show();
} else if(!myFile.exists()){
Toast.makeText(Editor.this, "<<<< this file does not exist >>>> ",
Toast.LENGTH_LONG).show();
}
Toast.makeText(Editor.this, "audio file name is: "+ audioFilename,
Toast.LENGTH_LONG).show();
Are you sure have import java.io.File?
Try with :
String pathsd = Environment.getExternalStorageDirectory()+"/";
// so var pathsd will return "/mnt/sdcard/"
// then you must sure var audioFilename is Music/Jungle.mp3
File myFile = new File(pathsd + audioFilename);
Or are you sure with your path? if you not sure you can try give direct string path.
File myFile = new File("/mnt/sdCard/Music/Jungle.mp3");
Try to change this line
File myFile = new File(extStore.getAbsolutePath() + "audioFilename");
with
File myFile = new File(audioFilename);
I have run test with the same code and it is working well.
Here is the code I test with :
String audioFilename = "/sdcard/NewFolder/test1.jpg";
Toast.makeText(SimpleTest.this, "File name: " + audioFilename,
Toast.LENGTH_LONG).show();
// the code below always returns "this file does not exist"
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(audioFilename);
if(myFile.exists()){
Toast.makeText(SimpleTest.this, "<<<< this file exists, it is: "+audioFilename+" >>>>",
Toast.LENGTH_LONG).show();
} else if(!myFile.exists()){
Toast.makeText(SimpleTest.this, "<<<< this file does not exist >>>> ",
Toast.LENGTH_LONG).show();
}
Toast.makeText(SimpleTest.this, "audio file name is: "+ audioFilename,
Toast.LENGTH_LONG).show();
Hope it helps you.
Thanks.
You need to add permission in AndroidManifeast file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Edit :
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore+ "/Music/Jungle.mp3"); <---- try this
I'm just going to hazard a guess and assume that you are using a physical device to test your application. If this is true, your external storage may not be mounted (since you're using USB storage with the computer) so the file really doesn't exist according to the system. Try testing your code without the USB cord plugged in.
EDIT:
Remove the quotes around "audioFilename".
File myFile = new File(extStore.getAbsolutePath() + "audioFilename");
to
File myFile = new File(extStore.getAbsolutePath() + audioFilename);
Related
I want to write text to file in Android. I tried writing to sdcard and public part of internal storage. I always got FileNotFound exception. I tried to get path by Environment.getExternalStorageDirectory().getAbsolutePath() and by Environment.getExternalStoragePublicDirectory(Enviroment.DIRECTORY_DCIM).getAbsolutePath()(it does not metter the file is not a picture, I suppose) and both returned: "storage/emulated/0" and "storage/emulated/0/DCMI" respectively. I have also tried direct path "/sdcard/MyFile/output.txt" and "mnt/sdcard/MyFile/output.txt". I have checked on most stackoverflow.com answears in such topic but I got only code similar to mine. (like from here)
Example of my code (I tried more variations):
try {
File dir = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyFile");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "output.txt");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
stream.write(("some text").getBytes());
stream.close();
toast = Toast.makeText(context, "Saving file successful.", Toast.LENGTH_SHORT);
toast.show();
} catch (Exception e) {
toast = Toast.makeText(context, Environment.getExternalStorageDirectory().getAbsolutePath(), Toast.LENGTH_SHORT);
//toast = Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT);
toast.show();
}
You have to set the
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
permission in your AndroidManifest.xml file.
If you run your app on Android 6.0 or higher you have to request this permission at runtime.
Request App Permissions
I am sorry to all you guys to waste your time. The problem was in permission setting. Here is the answear.
I am using download manager to download the file. The code for downloading the file is as follow.
private String DownloadData(Uri uri, View v, String textview) {
long downloadReference;
// Create request for android download manager
dm = (DownloadManager)getContext().getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
//Setting title of request
request.setTitle(textview);
//Setting description of request
request.setDescription("Android Data download using DownloadManager.");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(getContext(), DIRECTORY_DOWNLOADS, File.separator + "Dr_Israr_Ahmad" + File.separator + textview+".mp3");
//Enqueue download and save into referenceId
downloadReference = dm.enqueue(request);
return null
}
The above code works fine. What i need to do now is if the file is already downloaded than i want my app to play it. The code which is used is
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3"));
File file = new File(path);
if(file.exists()){
Toast.makeText(getContext(),path+ "/n exists", Toast.LENGTH_SHORT).show();
} else if (!file.exists()) {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse("http://www.digitalsguide.com/mobile-apps/dr-israr-ahmad/audios/"+filename+".mp3");
String filepath = DownloadData(uri,view,filename);
}
but the problem is the condition is true even if the file doesn't exist. Is there a problem in my path ? kindly help me out,
I detected some strange behavior with exists time ago and changed it to isFile:
File file = new File(path);
if (file.isFile()) {
Toast.makeText(getContext(), path + "/n exists", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
// ...
}
I think the mobile, somehow, created a directory every time new File() was executed.
Check this.
Because getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) returns /storage/emulated/0/Android/data/<PACKAGE_ID>/files/Download. It's not the folder where DownloadManager downloads files when we set Environment.DIRECTORY_DOWNLOADS.
Try to put your path like the example shown below:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/" +filename);
Here filename is example.pdf
you can then check if file exists or not
.getExternalFilesDir(yourFilePath) creates a directory in your code. so use it like this.
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3");
public void reNameFileName(String filePath, String newFilename) {
String path = filePath;
String filename = path.substring( path.lastIndexOf( "/" ) + 1 );
File oldfile = new File(filename);
File newfile = new File(newFilename,".mp4");
/*oldfile.renameTo(newfile);*/
if (oldfile.renameTo(newfile)) {
Toast.makeText( VideoPlayActvity.this, "Rename succesful", Toast.LENGTH_LONG ).show();
} else {
Toast.makeText( VideoPlayActvity.this, "Rename failed", Toast.LENGTH_LONG ).show();
}
}
this is my code for rename file i am able to get old file name and try to replace it by new file name then each time it goes fail condition please suggest me where am doing mistake.
Have you given permission to the app in manifest file to write to external sd card? If not, like this.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also, you can get the file storage directory with the following.
File sdcard = Environment.getExternalStorageDirectory();
Then, to implement the whole thing
File sdcard = Environment.getExternalStorageDirectory();
File first = new File(sdcard,"first.txt");
File rename = new File(sdcard,"rename.txt");
first.renameTo(rename);
Because the file path should never be hardcoded into the program, but the above function should be used
String folder = Environment.getExternalStorageDirectory()+ "/books";
File file=new File(folder);
File[] f;
f=file.listFiles(); //////f==null;
Toast.makeText(getApplicationContext(), f[1].toString(),
Toast.LENGTH_SHORT).show();
I am not able to fix the error . I need to help. Thanks.
what you can do is you can have a check like below
String path = Environment.getExternalStorageDirectory().toString()+"/books";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
if(file!=null&&file.length>0){
Toast.makeText(getApplicationContext(), f[1].toString(), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "folder is empty", Toast.LENGTH_SHORT).show();
}
what above code is doing basically it is checking that if length is greater the 0 and file objext is not null. that display the toast containing second file name in the list.
'file' is of File not Folder . That is why you can not get anything on calling file.listFiles() .
String path = Environment.getExternalStorageDirectory().toString()+"/books";
Log.d("Files", "Path: " + path);
File f = new File(path);
if (f.isDirectory()){
File file[] = f.listFiles();
Toast.makeText(getApplicationContext(), file[1].toString(), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "folder is empty", Toast.LENGTH_SHORT).show();
}
I think your directory path does not exists.
Check the documentation of File.listFiles(). It says
An array of abstract pathnames denoting the files and directories in
the directory denoted by this abstract pathname. The array will be
empty if the directory is empty. Returns null if this abstract
pathname does not denote a directory, or if an I/O error occurs.
You are giving a incorrect directory path, that is why file.listFiles(); is returning null.
As you are using Environment.getExternalStorageDirectory(), may be you have not enabled external storage for emulator. Just make sure that you have enabled external storage, this link will be helpful.
It's safer to check if f is null before accessing it:
if(f!=null){
Toast.makeText(getApplicationContext(), f[1].toString(),
Toast.LENGTH_SHORT).show(); // also size of f[], if you really want to access f[1]
}
I'm lost here.
I create files using this (stripped) code :
File dir = getBaseContext().getDir(dirPath, MODE_WORLD_WRITEABLE);
try {
File file = new File(dir, fileName);
FileOutputStream fous = new FileOutputStream(file);
fous.write(data);
fous.flush();
fous.close();
long l = file.length();
Log.i("PpCameraActivity", "File size : " + l);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error while trying to write photo file", Toast.LENGTH_LONG).show();
}
I can verify with logcat that my file seems to be created (it has a not null lenght). But I cannot see it when I connect my android device to my PC.
So... where is my file ? Is it hidden ? Erased ?
EDIT : I'm now trying to write on the SDCard specifically, using this :
File root = Environment.getExternalStorageDirectory();
File jpegFile = new File(root.getAbsolutePath() + "/myApplication/" + filePath);
try {
jpegFile.mkdirs();
FileOutputStream fous = new FileOutputStream(jpegFile);
fous.write(data);
fous.flush();
fous.close();
Log.i("PpCameraActivity", "File written : " + jpegFile.getAbsolutePath());
Toast.makeText(getBaseContext(), "File written : " + jpegFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
long l = jpegFile.length();
Log.i("PpCameraActivity", "File size : " + l);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error while trying to write photo file", Toast.LENGTH_LONG).show();
}
But I get a FileNotFoundException on the FileOutputStream creation...
OK found it.
Not an Android problem but just my error (not the first time) : mkdirs must be applied to the parent file, not the file I want to write...
So, for people interested :
Access the sd card using
File root = Environment.getExternalStorageDirectory();
Don't forget to require this permission
WRITE_EXTERNAL_STORAGE
Then make, as usual, mkdirs and file creation.
And don't forget : the android device cannot write on the sdard while it is mounted on you PC.
You probably aren't writing to the SD card, and the SD contents are all you can see from a USB connection.
Try something like this: http://androidgps.blogspot.com/2008/09/writing-to-sd-card-in-android.html (just the first thing that came up when I searched for "Android write to SD card").