I am creating folders using mkdirs() method. Before that, i am also checking if folder is already present or not. if not then only create. It works fine almost all devices but somehow its not creating in some devices.
I also checked runtime permission and storage access framework before creating folders. its all good still it does not create folders. Below is the sample path of creating folders:
Path: /storage/emulated/0/MyAppFolder/TestFolder
Here, /storage/emulated/0/ is internal storage path. After that i am creating two folders using below code:
val folder = File(Path)
if (!folder.exists()) {
if(!folder.mkdirs()){
Log.e("MyActivity","Folder not created")
}
}
I also tried using below code:
val folder = File(Path)
if (!folder.parentFile.exists()) {
if(!folder.parentFile.mkdirs()){
Log.e("MyActivity","Folder not created")
}
}
But still not working.
As per the getFilesDir() documentation, you should never assume a hardcoded installation or directory path - you should only be using relative paths compared to one of the storage directories
Related
I added some folder inside Emulator's SD Card from File Explorer. However, I have been having a hard time locating this folder programmatically to access contents inside the directory. From the image below, say I want to get path to "BiometricImages" folder. How can I do so.
This approach I use does not work for me.
val directory = appContext.getExternalFilesDir("BiometricImages")
val images = Files.walk(Paths.get(Environment.getExternalStorageDirectory().path + "/BiometricImages"), 5).filter { it.absolutePathString().endsWith(".jpg") }.toList()
I am using this code to access some contents inside the directory. The results recognizes that the directory is present but for a strange reason, it doesnt recognize the contents inside the directory. Always returns empty. However, it works on real device
I need to create 2 directories in my android application,
I can use this code to create a directory just fine
File m_Dir = new File(getFilesDir() + "/randomDir");
m_Dir.mkdir();
if (m_Dir.isDirectory()) {
Log.w("tag","randomDir dir is a directory");
}
however I cannot use this because it does not create a directory, no errors, but it just isn't a directory for some reason, even though the only thing that changed is the name of the file
File m_Dir = new File(getFilesDir() + "/dict");
m_Dir.mkdir();
if (m_Dir.isDirectory()) {
Log.w("tag","dict dir is a directory");
}
note they must be named "dict and "dbfiles", Using them for JWI wordnet, and thats how it locates the files it needs.
I have tried this many times with different names, and the only reason that this m_Dir.isDirectory returns false is because of the name, this doesn't make sense to me. The only reason I can think of, that this might fail is because I have file directories in my Assets folder with the same name.(I am copying these into my new directory so i can use them). I can change the name of the Asset folders (Probably what I'm going to do). However I created another folder in assets using a different name, I tried that name and it worked creating the directory using the same code as before. So that may not even be the problem. I was wondering wondering why this problem is occurring (No errors but no directory) and if there is any better way around it?
I have some level definitions in xml format (with .txt extension) inside (without any subfolders) my project's rescources folder
I for more scalability, I have a plain text file naming all these level definition XMLs
I read that file using
TextAsset WorldList = (TextAsset)Resources.Load("WorldList");
And then I load the needed world:
TextAsset TA = (TextAsset)Resources.Load(/*"LevelDefs/" +*/ Worlds[worldToload]);
xps.parseXml(TA.text);
loadLevel(levelToLoad);
(you see that I have moved these rescources out of subfolder to reduce the chance of them not loading)
worldToload here is the index number of that world
program works fine on windows but nothing loads on my android test device.
I seem to have problems debugging on device so I only guess something went wrong in loading phase.
any suggestions?
From Unity Documentation:
Most assets in Unity are combined into the project when it is built.
However, it is sometimes useful to place files into the normal
filesystem on the target machine to make them accessible via a
pathname. An example of this is the deployment of a movie file on iOS
devices; the original movie file must be available from a location in
the filesystem to be played by the PlayMovie function.
Any files placed in a folder called StreamingAssets in a Unity project
will be copied verbatim to a particular folder on the target machine.
You can retrieve the folder using the Application.streamingAssetsPath
property. It’s always best to use Application.streamingAssetsPath to
get the location of the StreamingAssets folder, it will always point
to the correct location on the platform where the application is
running.
So below snippet should work:
// Put your file to "YOUR_UNITY_PROJ/Assets/StreamingAssets"
// example: "YOUR_UNITY_PROJ/Assets/StreamingAssets/Your.xml"
if (Application.platform == RuntimePlatform.Android)
{
// Android
string oriPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Your.xml");
// Android only use WWW to read file
WWW reader = new WWW(oriPath);
while ( ! reader.isDone) {}
realPath = Application.persistentDataPath + "/Your"; // no extension ".xml"
var contents = System.IO.File.ReadAll(realPath);
}
else // e.g. iOS
{
dbPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Your.xml");
}
Thanks to David I have resolved this problem.
for more precision I add some small details:
1-As David points out in his answer (and as stated in unity documentations), we should use StreamingAssets if we want to have the same folder structure. One should use Application.streamingAssetsPathto retrieve the path.
However, files are still in the apk package in android's case, so they should be accessed using unity android's www class.
a good practice here is to create a method to read the file (even mandatory if you are going to read more than one file)
here is one such method:
private IEnumerator LoadDataFromResources(string v)
{
WWW fileInfo = new WWW(v);
yield return fileInfo;
if (string.IsNullOrEmpty(fileInfo.error))
{
fileContents = fileInfo.text;
}
else
fileContents = fileInfo.error;
}
This is a coroutine, and to use it we need to call it using
yield return StartCoroutine(LoadDataFromResources(path + "/fileName.ext"));
Yet another remark: we can not write into this file or modify it as it's still inside the apk package.
I am developing an android application. I need to create a folder in the internal memory, but when I try to create the folder I get the error below. I am running in an emulator.
mkdir failed for /mnt/New Folder , read only file system
I have tried many paths, but still the error persists. The only folder that I am able to create is called "cache", but I cannot browse it by my file chooser activity.
Any idea where is the suitable place to create folders without any permissions?
You can achieve it by this from a Context object (like Activity).
File files_folder = getFilesDir();
File files_child = new File(files_folder, "files_child");
files_child.mkdirs();
File created_folder = getDir("custom", MODE_PRIVATE);
File f1_child = new File(created_folder, "custom_child");
f1_child.mkdirs();
The function
getFilesDir()
will get the folder data/data/yourpackagename/files in internal memory. And the function
getDir("custom", MODE_PRIVATE)
will create a folder name app_custom in your app internal folder.
Answered by Minhtdh
I guess what you call internal memory is atualy the external memory (which can be open by
file chooser activity, the real internal memory only can be open if you have rooted)
If that true, you should chek those belows:
- first, you will need the write storeage permission in Manisfest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- then you should use `
String path =
Environment.getExternalStorageDirectory().getAbsolutePath() +
"/yourfoldername"
`
than
mnt/yourfoldername
at last you should use mkdirs to create folder than mkdir
Does Android not allow creating subdirectories in the cacheDir? Given that third party (such as advendors) surely will need to cache their own files, it makes lots of sense for me to create a subdirectory for my cached files and let third parties I've integrated manage their own cached files.
Does anyone know how to set the permissions so you can create subdirectories?
Ex. the following code appears to always fail to create a subdirectory.
File cacheDir = context.getCacheDir();
File subDir = new File(cacheDir, "subdir");
if ( !subDir.exists() ) {
if ( !subDir.mkdirs() )
Log.w(TAG, "Failed to create subdirectory in cache");
}
I just tried, I created subfolder successfully inside the cache folder.
I'm assuming maybe you've gotten a folder with the same name, maybe that's why you failed to mkdir?