Android How to get the root directory from a file (path) - java

How do I get the root directory of any path. If i have file path
/storage/emulated/0/Android/media/com.google.android.talk/Ringtones/, what is the best way for me to return the root directory "storage".
Is the file path always in "/" format, is that safe to split the path based on the character "/" or is there a built in function that I can call?
I need to create a method to return the root files of all the audio files on the android phone.
Here are some paths that I have and I want to start with the root directory and then browse each directory with audio files, so is there any build in method that I can call that will return the first directory?
/storage/emulated/0/media/audio/ringtones/abc.mp3
/storage/emulated/0/Music/Various Artists/music.mp3
/storage/emulated/0/new/Artists/test.mp3
Thanks.

What you are suggesting would work. One way would be to use substring with indexOf.
rootPath = string.substring(0, string.indexOf("/"));

You can access the root folder from ".apk" as follows:
java.io.File dir = new java.io.File("/storage/emulated/0");
and, can create subfolders with:
void CreateDir() throws IOException {
java.io.File dir = new java.io.File("/storage/emulated/0/MyApplication");
dir.mkdir();
}
Normally, you must have write permissions to do this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
But the problem starts with Android 10 (API level 29) and newer. Each path is null.
To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps.

Related

Android create folder in internal root directory

I need to create a folder in internal memory root directory and create a file inside it, but cannot find the below code working.
String path = Environment.getRootDirectory().toString();
File mFolder = new File(path,"Folder");
if (!mFolder.exists()) {
boolean res = mFolder.mkdir();
}
And mkdir always return false. I already found getDataDirectory() and getFilesDir() but that I doesn't required. I need to create a directory where the internal memory root location(location we see first when we open internal memory)
Edit:
Root folder I mean the first location we see on internal memory open using file browser. Where I can see Download ,Pictures ,Android etc..
You should use getExternalStorageDirectory() and you should ask for write permissions to it.
But note getExternalStorageDirectory() was deprecated on android 29, that means you should use getExternalFilesDir(), getExternalCacheDir(), or getExternalMediaDir() instead if you target a newer android version depending on the contents of your files.
And you should ask for write permissions on the manifest (for old android versions, Build.VERSION.SDK_INT < 23) and ask for them on run time (for newer android versions, Build.VERSION.SDK_INT >= 23)
To check if the user has granted permission of external storage:
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission granted");
//File write logic here
return true;
}
If the permission is not granted you should ask for it:
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
and implement OnRequestPermissionResult to get the result callback.
All this info and more code can be found here https://developer.android.com/training/permissions/requesting
Try below code
File file = new File(Environment.getExternalStorageDirectory() + "/Folder");
if (!file.exists()) {
boolean res = file.mkdirs();
}
But Environment.getExternalStorageDirectory() It's deprecated for Android Q.
I hope this can help you!
Thank You.
I think you can't create a directory inside the internal storage of the device. Except you've a root access for the app.
You can only create the directory inside your app private folder within the following path String path = getFilesDir().
you can use like this below -
File mydir = context.getDir("mydirectory", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myAwesomeFile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.
getDir(StringName, int mode) method to create or access directories in internal storage.
For more information you can read about this - create directory
mkdir()creates only the demanded directory and will return false if some of the parent directories doesn't exist. Try checking if the directories exist(or why not) or use mkdirs() which additionally creates the missing directiories

android : how to create new Directory in my package path

How can I make a new directory in the package that's stored in
storage/emulated/0/Android/data/getPackageName()/files/new-folder-name
so I can store converted videos and some pictures for my application?
I want to get the path of the installed package name and set it hardcore ;
If it's in the external storage, you can access a directory which is part of your app in a few ways:
Internal storage via Context#getDir(name, mode) if the files aren't big. This is always guaranteed
External storage via Context#getExternalFilesDir(name). This is not always guaranteed to be present.
Then from there you can create a new directory by:
File externalFilesDir = context.getExternalFilesDir("");
File file = new File(externalFilesDir, name);
//Create the new directory
boolean result = file.mkdir();
This way I detect the Dir of the App and use it to save files and so on.
AppName.getAppContext().getFilesDir();
or
AppName.getAppContext().getExternalFilesDir(null);
Don't forget to check for existence of the Dir.
getExternalFilesDir(Environment.DIRECTORY_DCIM).getPath() +
File.separator;

Unable to check if file exists or not in web project

I have a pdf file in my web project at the below location :
"static/Downloadables/20/Home_insurance_booklet.pdf "
"static" is present in the WebContent. The context root of the project is "pas".
In one of the jsp, I need to check if the file Home_insurance_booklet.pdf exists or not. I tried in many ways but unable to succeed. Below is the code I have used.
String filePath = request.getContextPath()+"/static/Downloadables/20/Home_insurance_booklet.pdf";
if(new File(filePath.toString()).exists()) {
------
}
Through the file exists, the condition is returning false. How to check if the file exists or not w.r.t to certain location in the root of the web project ?
Edit:
File path displayed is
/pas/static/Downloadables/20/Home_insurance_booklet.pdf
Try the following:
String path = getServletContext().getRealPath("/static/Downloadables/20/Home_insurance_booklet.pdf")
File file = new File(path)
if (file.exists()) {
// Success
}
And here is the API-Doc of getRealPath():
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
Use
ServletContext context = request.getServletContext();
StringBuilder finalPathToFile = new StringBuilder(context.getRealPath("/"));
The ServletContext#getRealPath() converts a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.
The "/" represents the web content root.
After that append in this way :
finalPathToFile.append("/static/Downloadables/20/Home_insurance_booklet.pdf");
Then use
if(new File(finalPathToFile.toString()).exists()) {
---------------------
doWhateverYouWantToDo
---------------------
}
check whether file is loaded in the project or not. and then try for absolute path first of the file in your code then try for relative path.
You have to use a file system based URL instead of relative web based URL.

Relative to absolute path in java

I have have a file that I want to use in my project which is in the resources package
src.res
Following what was stated in this answer, I believe that my code is valid.
File fil = new File("/res/t2.nii");
// Prints C:\\res\\t2.nii
System.out.println(fil.getAbsolutePath());
The problem is that I that file is in my projects file not there, so I get an Exception.
How am I suppose to properly convert from relative path to absolute?
Try with directory first that will provide you absolute path of directory then use file.exists() method to check for file existence.
File fil = new File("res"); // no forward slash in the beginning
System.out.println(fil.getAbsolutePath()); // Absolute path of res folder
Find more variants of File Path & Operations
Must read Oracle Java Tutorial on What Is a Path? (And Other File System Facts)
A path is either relative or absolute.
An absolute path always contains the root element and the complete directory list required to locate the file.
For example, /res/images is an absolute path.
A relative path needs to be combined with another path in order to access a file.
For example, res/images is a relative path. Without more information, a program cannot reliably locate the res/images directory in the file system.
Since you are using a Java package, you must to use a class loader if you want to load a resource. e.g.:
URL url = ClassLoader.getSystemResource("res/t2.nii");
if (url != null) {
File file = new File(url.toURI());
System.out.println(file.getAbsolutePath());
}
You can notice that ClassLoader.getSystemResource("res/t2.nii") returns URL object for reading the resource, or null if the resource could not be found. The next line convertes the given URL into an abstract pathname.
See more in Preferred way of loading resources in Java.
validate with
if (fil.exists()) { }
before and check if it really exist. if not then you can get the current path with
System.getProperty("user.dir"));
to validate that you are starting fromt he proper path.
if you really want to access the path you shouldnt use absolut pathes / since it will as explained start from the root of your Harddisk.
you can get the absolut path of the res folder by using this what my poster was writte in the previous answer:
File fil = new File("res");
System.out.println(fil.getAbsolutePath());

Make directory in android

Im trying to build a directory called "images" on the SD card on android. This is my code but its not working? Can anyone give me some advice?
File picDirectory = new File("mnt/sdcard/images");
picDirectory.mkdirs();
Update: Since Android 10,11 Storage updates, Google has restricted Storage access through standard programming language file operations.
For applications targeting only Android 10 (API 29) and above, you need to declare "requestLegacyExternalStorage="true" " in your android manifest file to use programming language based file operations.
<application
android:requestLegacyExternalStorage="true"
....>
==========
You want to be sure you are correctly finding the address of your SDCard, you can't be sure its always at any particular address. You will want to do the following!
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"images");
directory.mkdirs();
Let me know if this works for you!
You will also need the following line in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I use this to know the result:
File yourAppDir = new File(Environment.getExternalStorageDirectory()+File.separator+"yourAppDir");
if(!yourAppDir.exists() && !yourAppDir.isDirectory())
{
// create empty directory
if (yourAppDir.mkdirs())
{
Log.i("CreateDir","App dir created");
}
else
{
Log.w("CreateDir","Unable to create app dir!");
}
}
else
{
Log.i("CreateDir","App dir already exists");
}
you can use this :
File directory = new File(Environment.getExternalStorageDirectory() + "/images");
directory.mkdirs();
Environment.getExternalStorageDirectory() is deprecated. So you should use this:
File directory = new File(this.getExternalFilesDir(null).getAbsolutePath() + "/YourDirectoryName");
directory.mkdirs();
One thing that is worth noting is if you always get false from the mkdirs(), try to unplug your device from pc, and see if it could create folders. At least I tried, it worked for me, currently I'm looking for ways to fix this problem.
To create specific root directory and its sub folder i use this code
String root = Environment.getExternalStorageDirectory().toString();//get external storage
File myDir = new File(root + "/grocery"+"/photo/technostark");//create directory and subfolder
File dir=new File(root + "/grocery"+"/data");//create subfolder
myDir.mkdirs();
dir.mkdirs();
To create file inside sd card you have to use Environment.getExternalStorageDirectory()
/**
* Creates a new directory inside external storage if not already exist.
*
* #param name The directory name
*/
public static void createNewDirectory(String name) {
// create a directory before creating a new file inside it.
File directory = new File(Environment.getExternalStorageDirectory(), name);
if (!directory.exists()) {
directory.mkdirs();
}
}
Following two important parameter which helps you to create directory
1. directory.mkdirs() :
Creates the directory named by this file, creating missing parent
directories if necessary.
2. directory.mkdir() :
Creates the directory named by this file, assuming its parents exist.
For more you can how getExternalStorageDirectory() works please see link
This should help.
First get the path of the external storage:
File root=Environment.getExternalStorageDirectory();
Then:
File picDirectory = new File(root.getAbsolutePath(), "mnt/sdcard/images");
picDirectory.mkdirs();

Categories