I want to return true if filename exists regardless its extension.
I am using following method:
File file = new File(Environment.getExternalStorageDirectory() + Images/","filename.*");
if(file.exists())
{
return true;
}
There is a jpg file in this directory, if I search for "filename.jpg", it returns true, but in case of "filename.*" it returns false.
Is there any way to return true if filename is same but with any extension?
Try this
File Imagefolder = new File(Environment.getExternalStorageDirectory() + "Images/");
File[] listOfFiles = Imagefolder.listFiles();
for (File file : listOfFiles)
{
if (file.isFile())
{
String[] filename = file.getName().split("\\.(?=[^\\.]+$)"); //split filename from it's extension
if(filename[0].equalsIgnoreCase("filename"))
// file exists do what ever you want to do
}
}
Related
I have an requirement on my app that is , i have to track the file path and second i have to track the time of the file if that file is opened in some other application . I had researched everything but still not figuring out how to start . I know it's challenging and brain stroke implementation , but i need proper idea to move ahead .
I have achieved to create a file (file is of any kind .pdf/.docs etc)inside a folder . Now what i need if any one open the file in any other app then i have to first get the path of the file and secondly i have to track the time at what time the file is opened and closed . Here is the way i created the folder and dumped the file inside it . Now i have to read the file path and file opened in other app .
#Override
protected File doInBackground(FileMetadata... params) {
FileMetadata metadata = params[0];
//pathOfFileToSaved --> eg flight/ticket/vilash.pdf , flight/other/suman.docs
String folder_name = pathOfFileToSaved;
// File f = new File(Environment.getExternalStorageDirectory(), folder_main);
try {
File path = new File(Environment.getExternalStorageDirectory() + "/" + folder_name);
Log.e("pathoffile",""+path);
File file = new File(path, metadata.getName());
// Make sure the Downloads directory exists.
if (!path.exists()) {
if (!path.mkdirs()) {
mException = new RuntimeException("Unable to create directory: " + path);
}
} else if (!path.isDirectory()) {
mException = new IllegalStateException("Download path is not a directory: " + path);
return null;
}
// Download the file.
try (OutputStream outputStream = new FileOutputStream(file)) {
mDbxClient.files().download(metadata.getPathLower(), metadata.getRev())
.download(outputStream);
}
// Tell android about the file
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
mContext.sendBroadcast(intent);
return file;
} catch (DbxException | IOException e) {
mException = e;
}
return null;
}
I wanted to download images that are downloaded from Dropbox and cache them for further use:
String cachePath = mContext.getCacheDir().getAbsolutePath() + entry.fileName();
File cacheFile = new File(cachePath);
//cacheFile.exists() returns true after 1st call
if(!cacheFile.exists()){
//If cache doesn't exist, download the file
mFos = new FileOutputStream(cachePath);
mApi.getThumbnail(path, mFos, ThumbSize.BESTFIT_320x240,
ThumbFormat.JPEG, null);
}
mDrawable = Drawable.createFromPath(cachePath);
mImageView.setImageDrawable(mDrawable);
The mDrawable is null if the code doesn't enter the if block.
If I comment the if condition it works fine. But downloads the images every time.
Edit:
The above code is from how to test for a file in cache
Try this hope helps you
String path = context.getFilesDir().getAbsolutePath() + File.separator + entry.fileName();
File file = new File(path);
if (file.exists()) {
// File exists
} else {
// File does not exist
}
I want to make dir in Sdcard, and i do follow:
I added: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in manifest.
I get root_path by: public static final String ROOT_PATH = Environment.getExternalStorageDirectory().toString() + "/Hello_World/"; and it returns
/storage/emulated/0/Hello_World (getting when debug).
Next, I run this code:
File file = new File(Constants.ROOT_PATH);
int i = 0;
while (!file.isDirectory() && !file.mkdirs()) {
file.mkdirs();
Log.e("mkdirs", "" + i++);
}
I also tried both mkdirs() and mkdir() but it's showing endless loop in logcat (Log.e("mkdirs", "" + i++);). Sometimes it work, but sometimes not.
Thanks for you helping!
Update: I tried my code for some devices: Nexus4, nexus7, Vega Iron, Genymotion, LG G Pro, then just Vega Iron work as expected. ??!!?!?
Try like this it will create a folder in the sd card
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/hello_world");
myDir.mkdirs();
If you want to check that file exists or not use this code
File file = new File (myDir, file_name);
if (file.exists ())
// file exist
else
// file not exist
For reference look at this answer Android saving file to external storage
The error is cause by && in while (!file.isDirectory() && !file.mkdirs()) it should be while (!file.isDirectory() || !file.mkdirs()). You should also check if the media is mounted.
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
if (DEBUG) {Log.d(TAG, "createSoundDir: media mounted");} //$NON-NLS-1$
File externalStorage = Environment.getExternalStorageDirectory();
if (externalStorage != null)
{
String externalStoragePath = externalStorage.getAbsolutePath();
File soundPathDir = new File(externalStoragePath + File.separator + "Hello_World"); //$NON-NLS-1$
if (soundPathDir.isDirectory() || soundPathDir.mkdirs())
{
String soundPath = soundPathDir.getAbsolutePath() + File.separator;
if (DEBUG) {Log.d(TAG, "soundPath = " + soundPath);} //$NON-NLS-1$
}
}
}
Cut and paste from one of my project.
Thank all you guys, finally i found out the problem. The problem is in the while() loop, I replace by
if
(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
&& !file.isDirectory()) {
file.mkdirs(); }
Use Environment.getExternalStorageDirectory().getAbsolutePath() as below...
public static final String ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Hello_World/";
And Check that SDCard is mounted before creating directory as below....
File file = new File(Constants.ROOT_PATH);
int i = 0;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if(!file.exists()) {
file.mkdir();
}
}
Both files are present on the sdcard, but for whatever reason exists() returns false the the png file.
//String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png";
String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-1200240592.pdf";
File file2 = new File(path);
if (null != file2)
{
if(file2.exists())
{
LOG.x("file exist");
}
else
{
LOG.x("file does not exist");
}
}
Now, I've look at what's under the hood, what the method file.exists() does actually and this is what it does:
public boolean exists()
{
return doAccess(F_OK);
}
private boolean doAccess(int mode)
{
try
{
return Libcore.os.access(path, mode);
}
catch (ErrnoException errnoException)
{
return false;
}
}
May it be that the method finishes by throwing the exception and returning false?
If so,
how can I make this work
what other options to check if a file exists on the sdcard are available for use?
Thanks.
1 You need get the permission of device
Add this to AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2 Get the external storage directory
File sdDir = Environment.getExternalStorageDirectory();
3 At last, check the file
File file = new File(sdDir + filename /* what you want to load in SD card */);
if (!file.canRead()) {
return false;
}
return true;
Note: filename is the path in the sdcard, not in root.
For example: you want find
/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
then filename is
./Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
.
Please try this code. Hope it should helpful for you. I am using this code only. Its working fine for me to find the file is exists or not. Please try and let me know.
File file = new File(path);
if (!file.isFile()) {
Log.e("uploadFile", "Source File not exist :" + filePath);
}else{
Log.e("uploadFile","file exist");
}
Check that USB Storage is not connected to the PC. Since Android device is connected to the PC as storage the files are not available for the application and you get FALSE to File.Exists().
Check file exist in internal storage
Example : /storage/emulated/0/FOLDER_NAME/FILE_NAME.EXTENTION
check permission (write storage)
and check file exist or not
public static boolean isFilePresent(String fileName) {
return getFilePath(fileName).isFile();
}
get File from the file name
public static File getFilePath(String fileName){
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "FOLDER_NAME");
File filePath = new File(folder + "/" + fileName);
return filePath;
}
This is the code i am using to create a folder in the default pictures folder:
File imagesFolder = new File(Environment.DIRECTORY_PICTURES, "/images");
if (!imagesFolder.exists()) {
Log.d("if imagesFolder exists - 1", "False");
imagesFolder.mkdirs();
} else {
Log.d("if imagesFolder exists - 1", "True");
}
if (!imagesFolder.exists()) {
Log.d("if imagesFolder exists - 2", "False");
imagesFolder.mkdirs();
} else {
Log.d("if imagesFolder exists - 2", "True");
}
in log i am getting:
False
False
for the 1st time the directory is not present, hence False but then immediately i am creating it using mkdirs(), hence i expect the 2nd log to be True but even that is False and my application crashed because of NullPointerException in the later part of the code
Please help
Thank You
You are using Environment.DIRECTORY_PICTURES the wrong way. It's just a String constant like "Pictures" but not a path. You need to get the path via Environment.getExternalStoragePublicDirectory(string)
File pictureFolder = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
);
File imagesFolder = new File(pictureFolder, "images");
// etc
To generate a folder at first you need to add permission at AndroidMinifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Now call following method to create a new folder with in which Directory you want to create your folder(this name should exist in Environment. list) and your folder name.
File outputDirectory = GetPhotoDirectory(Environment.DIRECTORY_PICTURES, "YourFolder");
Generate your folder by this method
public static File GetDirectory(String inWhichFolder, String yourFolderName ) {
File outputDirectory = null;
String externalStorageState = Environment.getExternalStorageState();
if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
File pictureDirectory = Environment.getExternalStoragePublicDirectory(inWhichFolder);
outputDirectory = new File(pictureDirectory, yourFolderName);
if (!outputDirectory.exists()) {
if (!outputDirectory.mkdirs()) {
Log.e(LogHelper.LogTag, "Failed to create directory: " + outputDirectory.getAbsolutePath());
outputDirectory = null;
}
}
}
return outputDirectory;
}
If you want to create a file under your newly created folder then you can use below code
public static Uri GenerateTimeStampPhotoFileUri(File outputDirectory, String fileName){
Uri photoFileUri = null;
if(outputDirectory!=null) {
File photoFile = new File(outputDirectory, fileName);
photoFileUri = Uri.fromFile(photoFile);
}
return photoFileUri;
}
Call to create a file after creating the folder with File Directory. It will return your file Uri
Uri fileUri = GenerateTimeStampPhotoFileUri(outputDirectory, fileName);