Android check existence of file in android internal storage - android

I put some .mp4 file in a folder in my android device internal storage. And then I play this file from my application. It plays well if exists otherwise app crushed.
So before play file I want to check its existence.
I tried below code but no luck.
File file = new File("file:///storage/emulated/0/tutorial/1a1cbfc4-18cb-4637-8405-01bf9bebeda3.mp4");
if (file.exists()) {
LogUtil.printLogMessage(VideoListActivity.class.getName(), "video File", "file exist");
} else {
LogUtil.printLogMessage(VideoListActivity.class.getName(), "video File", "file not exist");
}
i am sure the file is exist in the folder named tutorial in my internal storage.

Use file.isFile() for file & file.isDirectory() for directory,
file.exists() tries to access the file which causes it to crash if the file doesn't exist, file.isFile() uses linux stat, which only returns the information about the file without trying to access it.

Please make proper file name, Replace with File myDirectory = new File(Environment.getExternalStorageDirectory(), dirName);
public Boolean checkFile(){
File file = new File("/storage/emulated/0/tutorial/1a1cbfc4-18cb-4637-8405-01bf9bebeda3.mp4");
if (file.exists()) {
return true;
} else {
return false;
}
}
Use checkfile True/False flag before video play.

Try this
File file = new File(path);
if (!file.isFile()) {
}else{
}

Related

Android - Missing files between file explorers

I'm trying to access the two files, Spring v2.json and Test.json, in my Android app. However, I will add them using Windows with my phone connected, but when I run my app, the file seems to disappear.
Getting the file
File file = new File(getExternalFilesDir(null), "Spring v2.json");
Check is the file exists
if (file.exists()) {
TransferObserver observer = transferUtility.download(
"easelbucket", // bucket to download from
"sections/" + objectKey, // key for object to be downloaded
file // file to download object to
);
} else {
Toast.makeText(this, "File does not exist", Toast.LENGTH_SHORT).show();
return null;
}
I know that the file stops existing because (1) the if statement enters the else block, and (2) the app crashes when it attempts to use the result of the file.
File file = new File(getExternalFilesDir(null), "/Spring v2.json")
You forget slash before filename.
Also check if
.canRead();
and
.canExecute();

How to Create a folder in external sdcard in Android 4.4.2(Kitkat) API level 19

I try a lot to create a folder in SD card in android 4.4.2 version.
i try the following code
String dirName="Test";
File file = new File(Environment.getExternalStorageDirectory(), dirName);
boolean status = file.mkdir();
if (status)
Toast.makeText(MainActivity.this,
"Directory created successfully", Toast.LENGTH_SHORT)
.show();
else
Toast.makeText(MainActivity.this, "Directory create failed",
Toast.LENGTH_SHORT).show();
but it creates a folder in internal storage.
and I try another code is
String path=System.getenv("SECONDARY_STORAGE");
File file=new File(path +"/Test123");
file.mkdir();
it creates a folder in External SDCARD in android 4.1 but not in android 4.4.2
So how can i create a folder in External sdcard in android 4.4.2??
If anyone know please help me..
Thanks in advance
The documentation states that
Applications should not directly use this top-level directory, in
order to avoid polluting the user's root namespace. Any files that are
private to the application should be placed in a directory returned by
Context.getExternalFilesDir, which the system will take care of
deleting if the application is uninstalled.
where with top-level directory they mean the return value of Enviroment.getExternalStorageDirectory()
Using getExternalFilesDir you will have
File file = new File (getExternalFilesDir(null), dirName);
if (!file.exists()) {
boolean status = file.mkdir();
if (status) {
Toast.makeText(MainActivity.this, "Directory created successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Directory create failed", Toast.LENGTH_SHORT).show();
}
}
also you should be aware of the fact that mkdir() returns false if the directory already exists
This should be self-explanatory.
String folderName = "NewFolder";
File file = new File(Environment.getExternalStorageDirectory(),
folderName);
if (!file.exists()) {
file.mkdirs();
}
Make sure you have added WRITE_EXTERNAL_STORAGE permission in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Credits to Dhaval

android - file.exists() returns false for existing file (for anything different than pdf)

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;
}

Can I see the file created in Android Tablet by file.createNewFile()?

I created a file by file.createNewFile() command in "data/data/com.android.bonvoyage" folder to test file creation in the internal storage of my android tablet.
I found that the file should be visible when I have root account, but I want to find a way
to see the file created without root permission.
I don't care where the file is created, just want to see and test it on actual tablet.
Can I do that?
The process was successful by
File file = new File("data/data/com.android.bonvoyage/myfile.txt");
boolean tf = false;
if (!file.exists()) {
try {
tf = file.createNewFile();
} catch (IOException ioe) {
Toast.makeText(this, ioe.toString(), 5000).show();
//ioe.printStackTrace();
} finally {
Toast.makeText(this, "File Created? " + Boolean.toString(tf), Toast.LENGTH_SHORT).show();
}
}
With root explorer or any file explorer that supports root you could browse to: data/data/com.android.bonvoyage/myfile.txt and look whether its there or not?
Write the file to the sdcard and then you can see it with the file browser without root permissions.
Use the following code (taking from the android guide) to open a file in the pictures folder for example:
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
The full guide can be found here:
http://developer.android.com/training/basics/data-storage/files.html#WriteExternalStorage

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
}

Categories

Resources