I'm checking if the database in a folder of the device exists. The folder and the database exists, but is not found. The path is right, then where am I wrong?
private void checkDBexists() {
File internal = Environment.getExternalStorageDirectory();
File myFile = new File(internal.getAbsoluteFile() + "MyFolder/database.db");
if (myFile.exists()) {
importaDB();
} else {
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "not work", Toast.LENGTH_SHORT);
toast.show();
}
}
File myFile = new File(internal.getAbsoluteFile()+"/MyFolder/database.db");
Add "/" before MyFolder.
Related
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
I want to check whether the file is already exists in Download folder in Android. I'm using Android download manager to download the file. In there if section is not working. If file is already there (Ex: File name - songname.mp3), when downloading the same file for the second time it's downloading the file as songname1.mp3. I have tried the code below. I want to show a message if the file is already there.
Please help me to fix this issue.
public void DownloadChecker() {
File applictionFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+ "/"+"mysongs.mp3");
if(applictionFile.exists()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
} else {
String servicestring = Context.DOWNLOAD_SERVICE;
DownloadManager downloadmanager;
downloadmanager = (DownloadManager) getSystemService(servicestring);
Uri uri = Uri.parse(DownloadUrl);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalFilesDir(MainActivity.this,
Environment.DIRECTORY_DOWNLOADS,"mysongs.mp3");
Long reference = downloadmanager.enqueue(request);
}
}
change
if(applictionFile.exists()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
to
if(applictionFile.canRead()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
or
if(applictionFile.isFile()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
Try in simple way
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do your code stuff
}
You should probably try changing:
File applictionFile = new File(Environment.
getExternalStoragePublicDirectory(Environment
.DIRECTORY_DOWNLOADS)+ "/"+"mysongs.mp3");
to:
File applictionFile = new File(Environment.
getExternalStoragePublicDirectory(Environment
.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + "mysongs.mp3");
on which testing device are you testing your app? is it above api-23 then you should have to set permission at the run time ! or else try this
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "/mysongs.mp3");
if(myFile.exists()){
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
I cannot create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String Path = Environment.getExternalStorageDirectory().getPath().toString()+ "/Shidhin/ShidhiImages";
System.out.println("Path : " +Path );
File FPath = new File(Path);
if (!FPath.exists()) {
if (!FPath.mkdir()) {
System.out.println("***Problem creating Image folder " +Path );
}
}
Do it like this :
String folder_main = "NewFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
If you wanna create another folder into that :
File f1 = new File(Environment.getExternalStorageDirectory() + "/" + folder_main, "product1");
if (!f1.exists()) {
f1.mkdirs();
}
The difference between mkdir and mkdirs is that mkdir does not create nonexistent parent directory, while mkdirs does, so if Shidhin does not exist, mkdir will fail. Also, mkdir and mkdirs returns true only if the directory was created. If the directory already exists they return false
getexternalstoragedirectory() is already deprecated. I got the solution it might be helpful for you. (it's a June 2021 solution)
Corresponding To incliding Api 30, Android 11 :
Now, use this commonDocumentDirPath for saving files.
Step: 1
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step: 2
public static File commonDocumentDirPath(String FolderName){
File dir = null ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
dir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/"+FolderName );
} else {
dir = new File(Environment.getExternalStorageDirectory() + "/"+FolderName);
}
return dir ;
}
The use of Environment.getExternalStorageDirectory() now is deprecated since API level 29, the option is using:
Context.getExternalFilesDir().
Example:
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external
// storage.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
file.delete();
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
return file.exists();
}
I can create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String folder_main = "Images";
File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");
if (!outerFolder.exists()) {
outerFolder.mkdirs();
}
if (!outerFolder.exists()) {
inerDire.createNewFile();
}
outerFolder.mkdirs(); // This will create a Folder
inerDire.createNewFile(); // This will create File (For E.g .jpg
file)
we can Create Folder or Directory on External storage as :
String myfolder=Environment.getExternalStorageDirectory()+"/"+fname;
File f=new File(myfolder);
if(!f.exists())
if(!f.mkdir()){
Toast.makeText(this, myfolder+" can't be created.", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this, myfolder+" can be created.", Toast.LENGTH_SHORT).show();
}
and if we want to create Directory or folder on Internal Memory then we will do :
File folder = getFilesDir();
File f= new File(folder, "doc_download");
f.mkdir();
But make Sure you have given Write External Storage Permission.
And Remember that if you have no external drive then it choose by default to internal parent directory.
I'm Sure it will work .....enjoy code
If you are trying to create a folder inside your app directory in your storage.
Step 1 : Add Permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step 2 : Add the following
private String createFolder(Context context, String folderName) {
//getting app directory
final File externalFileDir = context.getExternalFilesDir(null);
//creating new folder instance
File createdDir = new File(externalFileDir.getAbsoluteFile(),folderName);
if(!createdDir.exists()){
//making new directory if it doesn't exist already
createdDir.mkdir();
}
return finalDir.getAbsolutePath() + "/" + System.currentTimeMillis() + ".txt";
}
This is raw but should be enough to get you going
// create folder external located in Data/comexampl your app file
File folder = getExternalFilesDir("yourfolder");
//create folder Internal
File file = new File(Environment.getExternalStorageDirectory().getPath( ) + "/RICKYH");
if (!file.exists()) {
file.mkdirs();
Toast.makeText(MainActivity.this, "Make Dir", Toast.LENGTH_SHORT).show();
}
Try adding
FPath.mkdirs();
(See http://developer.android.com/reference/java/io/File.html)
and then just save the file as needed to that path, Android OS will create all the directories needed.
You don't need to do the exists checks, just set that flag and save.
(Also see : How to create directory automatically on SD card
I found some another thing too :
I had the same problem recently, and i tryed abow solutions and they did not work...
i did this to solve my problem :
I added this permission to my project manifests file :
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
(plus READ and WRITE permissions) and my app just worked correctly.
try {
String filename = "SampleFile.txt";
String filepath = "MyFileStorage";
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText(myData);
response.setText("SampleFile.txt data retrieved from External Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
}
else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
i am trying to load a html file in webView from sd card its not working, Directory exists in SD card as well as file in it. Here is the code i have tried.
public void CheckReg()
{
File file = new File(getExternalCacheDir(), "Reginfo/input/register.html" );
if (file.exists())
{
index.loadUrl("file:///sdcard/Reginfo/input/register.html");
Toast.makeText(mContext, "File Exists", Toast.LENGTH_SHORT).show();
}
}
do this
File file = new File(Environment.getExternalStorageDirectory()+"/Reginfo/input/register.html");
if (file.exists())
{
index.loadUrl("file://"+Environment.getExternalStorageDirectory()+"/Reginfo/input/register.html");
dont forget to
add permissions to menifest
should set like ,
public void CheckReg()
{
File file = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath()+"Reginfo/input/register.html" );
if (file.exists())
{
index.loadUrl("file:///"+file);
Toast.makeText(mContext, "File Exists", Toast.LENGTH_SHORT).show();
}
}
You shouldn't hard code the directory of the sdcard like that. Its typically at /mnt/sdcard/ but this is never assured instead of this you can write it like this.
and before you load the file from sd-card you make ensure that sd-card is mounted.
You can use the following:
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d(TAG, "No SDCARD");
} else {
index.loadUrl("file://"+Environment.getExternalStorageDirectory()+"/Reginfo/input/register.html");
}
How do I check if a directory exist on the sdcard in android?
Regular Java file IO:
File f = new File(Environment.getExternalStorageDirectory() + "/somedir");
if(f.isDirectory()) {
....
Might also want to check f.exists(), because if it exists, and isDirectory() returns false, you'll have a problem. There's also isReadable()...
Check here for more methods you might find useful.
File dir = new File(Environment.getExternalStorageDirectory() + "/mydirectory");
if(dir.exists() && dir.isDirectory()) {
// do something here
}
The following code also works for java files:
// Create file upload directory if it doesn't exist
if (!sdcarddir.exists())
sdcarddir.mkdir();
General use this function for checking is a Dir exists:
public boolean dir_exists(String dir_path)
{
boolean ret = false;
File dir = new File(dir_path);
if(dir.exists() && dir.isDirectory())
ret = true;
return ret;
}
Use the Function like:
String dir_path = Environment.getExternalStorageDirectory() + "//mydirectory//";
if (!dir_exists(dir_path)){
File directory = new File(dir_path);
directory.mkdirs();
}
if (dir_exists(dir_path)){
// 'Dir exists'
}else{
// Display Errormessage 'Dir could not creat!!'
}
I've made my mistake about checking file/ directory. Indeed, you just need to call isFile() or isDirectory(). Here is the docs
You don't need to call exists() if you ever call isFile() or isDirectory().
Yup tried a lot, beneath code helps me :)
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "ur directory name");
if (!folder.exists()) {
Log.e("Not Found Dir", "Not Found Dir ");
} else {
Log.e("Found Dir", "Found Dir " );
Toast.makeText(getApplicationContext(),"Directory is already exist" ,Toast.LENGTH_SHORT).show();
}