Android; Check if file exists without creating a new one - android

I want to check if file exists in my package folder, but I don't want to create a new one.
File file = new File(filePath);
if(file.exists())
return true;
Does this code check without creating a new file?

Your chunk of code does not create a new one, it only checks if its already there and nothing else.
File file = new File(filePath);
if(file.exists())
//Do something
else
// Do something else.

When you use this code, you are not creating a new File, it's just creating an object reference for that file and testing if it exists or not.
File file = new File(filePath);
if(file.exists())
//do something

It worked for me:
File file = new File(getApplicationContext().getFilesDir(),"whatever.txt");
if(file.exists()){
//Do something
}
else{
//Nothing
}

When you say "in you package folder," do you mean your local app files? If so you can get a list of them using the Context.fileList() method. Just iterate through and look for your file. That's assuming you saved the original file with Context.openFileOutput().
Sample code (in an Activity):
public void onCreate(...) {
super.onCreate(...);
String[] files = fileList();
for (String file : files) {
if (file.equals(myFileName)) {
//file exits
}
}
}

The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists
File file = new File("FileName");
if(file.exists()){
System.out.println("file is already there");
}else{
System.out.println("Not find file ");
}

public boolean FileExists(String fname) {
File file = getBaseContext().getFileStreamPath(fname);
return file.exists();
}

if(new File("/sdcard/your_filename.txt").exists())){
// Your code goes here...
}

Kotlin Extension Properties
No file will be create when you make a File object, it is only an interface.
To make working with files easier, there is an existing .toFile function on Uri
You can also add an extension property on File and/or Uri, to simplify usage further.
val File?.exists get() = this?.exists() ?: false
val Uri?.exists get() = File(this.toString).exists()
Then just use uri.exists or file.exists to check.

Related

Deleted file reappers in the File browser

When downloading a pdf file using DownloadManager, I want to delete it if it already exists in Environment.DIRECTORY_DOWNLOADS.
I check if file exists and delete it using these code:
private boolean fileExists(String fileName) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName);
return file.exists();
}
private boolean removeFile(String fileName) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName);
return file.delete();
}
removeFile() says that file is deleted, by returning true, and when I look into File Browser only one file is showing up. But when I delete that file it reappers on top of old one. What's wrong?
if i'm not wrong the File file= new File(...) will be your problem.
Because you are using the File class constructor, which is creates a new file to the exact location (File class documentation is here documentation).
Try to give your removeFile(String)method a File type variable, that should do the trick (or use some File 'getting' method from the documentation).

Why a File returned by ContextWrapper.getDir() always exists?

I am making an application in which I have to save video files internally(in app memory when app is uninstalled all the filed should also be uninstalled).For this I have read many articles and googled a lot and found different solutions and after that I made a method there I wrote the code for that here is the code
public static boolean checkIfAlreadyDownloaded(Context context, String rhymeName) {
ContextWrapper cw = new ContextWrapper(context);
File rhymeDirectory = cw.getDir(Constants.INTERNAL_DIRECTORY_NAME, Context.MODE_PRIVATE);
if (rhymeDirectory.exists()) {
File individualRhyme = new File(rhymeDirectory, rhymeName);
if (individualRhyme.exists())
return true;
}
return false;
}
Here Constants.INTERNAL_DIRECTORY NAME is "Rhymes"
what I understand is if there is no directory then it returns false but When I install my app first time it return true.Even I uninstalled it and then reinstall it is always returning true .My question is "why it is always returning true"? Shouldn't it return false first time?Correct me please if I am wrong.
ContextWrapper.getDir() creates the directory if necessary, as said in the documentation:
public File getDir (String name, int mode)
Retrieve, creating if needed, a new directory in which the application can place its own custom data files.
File mydir = context.getDir("mydir", Context.MODE_PRIVATE);
//Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myfile");
//Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir);
//Use the stream as usual to write into the file
For deleting a file from internal :
if (new File("path/to/file").delete()) {
// Deleted
} else {
// Not deleted
}

Check if file exists on SD card on Android

I want to check if a text file exists on the SD card. The file name is mytextfile.txt. Below is the code:
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
How can I check whether this file exists?
This should do the trick, I've replaced the hard coded SDcard reference to the recommended API call getExternalCacheDir():
File file = new File(getExternalCacheDir(), "mytextfile.txt" );
if (file.exists()) {
//Do action
}
See this file System in android : Working with SDCard’s filesystem in Android
you just check
if(file.exists()){
//
}
*Using this you can check the file is present or not in sdcard *
File file = new File(sdcardpath+ "/" + filename);
if (file.exists())
{
}
You have to create a file, and set it to be the required file, and check if it exists.
String FILENAME="mytextfile.txt";
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME);
if (fileToCheck.exists()) {
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
}
Have Fun!
The FileOutputStream constructor will throw a FileNotFound exception if the specified file doesn't exist. See the Oracle documentation for more information.
Also, make sure you have permission to access the SD card.
check IF condition with Boolean type like
File file = new File(path+filename);
if (file.exists() == true)
{
//Do something
}

check that given file is present on this path or not in Android Filesystem?

How can we check the given file is present in Android Filesystem or not without using File inputstream.because I only want to check the existence of the file on the given path.
File myFile = new File("/path/to/file");
if (myFile.isFile()) {
...
}
If you have created a file using openFileOutput method then this works
File mFile = new File(getBaseContext().getFilesDir(),FileName);
if (mFile.exists() )
{
//File is Exits.
}
else
{
//File is not Exits.
}
hope this helps

How to delete internal storage file in android?

I have used the Android internal storage to save a file for my application (using openFileOutput) but I would like to delete that file, is it possible and how?
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
I know this is a bit of an oldie, but the docs say to use:
deleteFile("filename");
rather than:
File.delete();
Which if you are already using:
getFilesDir();
kind of makes sense.
You should always delete files that you no longer need. The most straightforward way to delete a file is to have the opened file reference call delete() on itself.
myFile.delete();
If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling deleteFile():
myContext.deleteFile(fileName);
Note: When the user uninstalls your app, the Android system deletes the following:
All files you saved on internal storage
All files you saved on external storage using getExternalFilesDir().
However, you should manually delete all cached files created with getCacheDir() on a regular basis and also regularly delete other files you no longer need.
Source : http://developer.android.com/training/basics/data-storage/files.html
If you want to delete all files from a folder then use the following function:
private void deleteTempFolder(String dir) {
File myDir = new File(Environment.getExternalStorageDirectory() + "/"+dir);
if (myDir.isDirectory()) {
String[] children = myDir.list();
for (int i = 0; i < children.length; i++) {
new File(myDir, children[i]).delete();
}
}
}
Folder must be present on storage. If not we can check one more codition for it.
if (myDir.exists() && myDir.isDirectory()) {
//write same defination for it.
}
new File(mUri.toString).delete();
void clearMyFiles() {
File[] files = context.getFilesDir().listFiles();
if(files != null)
for(File file : files) {
file.delete();
}
}
Another alternative in Kotlin
val file: File = context.getFileStreamPath("file_name")
val deleted: Boolean = file.delete()
Use delete method of File

Categories

Resources