Make directory in android - java

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();

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;

Save a binary file in the same folder for every PC

I'm making a game that saves information into a binary file so that I can start at the point I left the game on the next use.
My problem is that it works fine on my PC because I chose a path that already existed to save the file, but once I run the game on another PC, I got an error saying the path of the file is invalid (because i doesn't exist yet, obviously).
Basically I'm using the File class to create the file and then the ObjectOutputStream and ObjectInputStream to read/write info.
Sorry for the noob question, I'm still pretty new to using files.
You must first check if the directory exists and if it does not exist then you must create it.
String folderPath = System.getProperty("user.home") + System.getProperty("file.separator") + "MyFolder";
File folder = new File(folderPath);
if(!folder.exists())
{
folder.mkdirs();
}
File saveFile = new File(folderPath, "fileName.ext");
Please note that the mkdirs() method is more useful in this case instead of the mkdir() method as it will create all non existing parent folders.
Hope this helps. Good luck and have fun programming!
Cheers,
Lofty
You are looking for File mkdirs()
Which will create all the directories necessary that are named in your path.
For example:
File dirs= new File("/this/path/does/not/exist/yet");
dirs.mkdir();
File file = new File(dirs, "myFile.txt");
Take in consideration that it may fail, due to proper file permissions.
My solution has been create a subdirectory within the user's home directory (System.getProperty("user.home")), like
File f = new File(System.getProperty("user.home") + "/CtrlAltDelData");
f.mkdir();
File mySaveFile = new File (f, "save1.txt");

How to save , read and write files in android in external storage?

I'm trying to understand how to work with files in Android
I have installed my android application in external storage
it contain a folder dataof files that it need while running...
firstly I think that my folder will saved automatically in the sdcard while installing
but after reading some question here , It seem I should create a folder in which I save my
folder data...
I write this question to ask about steps to do to achieve my goal an I need your advances
Goal
Save a folder data in external storage , read from it and write a new file
Steps
add permission to manifest file
create a folder in sdcard ==> how to place my folder there ?
create a new file , save it on sdcard and write into it
code
This is a part of my activity :
{
....
File file = new File ("...")
doPrediction(file);
}
private void doPrediction (String FileName)
{
for (File child : VisualModels.listFiles()) {
svmPredict.run(MyDataSource.inputPrediction,
new File( MyDataSource.outputPrediction+ "/"+child.getName()+".predict"),
child);
}
}
I declared the class svmPredict as any ordinary java class ans this is the code of run method
try
{
BufferedReader input = new BufferedReader(new FileReader(inputFile));
DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
svm_model model = new svm().svm_load_model(modelFile);
if(predict_probability == 1)
{
if(svm.svm_check_probability_model(model)==0)
{
System.err.print("Model does not support probabiliy estimates\n");
System.exit(1);
}
}
else
{
if(svm.svm_check_probability_model(model)!=0)
{
svm_predict.info("Model supports probability estimates, but disabled in prediction.\n");
}
}
predict(input,output,model,predict_probability);
input.close();
output.close();
}
Please read the Android documentation regarding External Storage.
Pay attention to the getExternalFilesDir(). You can retrieve the path to the external storage using this method.
When you have the path, you can use the File object to create the data folder on the external storage like this:
File dataDirectory = new File(getExternalFilesDir() + "/data/");
Then create the folder by applying the mkdirs()-method on the File object:
dataDirectory.mkdirs();
To write to external storage, you will indeed have to declare this in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

What is my directory when writing files in Android?

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
fos.write(string.getBytes());
fos.close();
When trying to delete one of those files, this is what I use, but it's returning false.
String tag = v.getTag().toString();
File file = new File(System.getProperty("user.dir")+"/"+tag);
String s = new Boolean (file.exists()).toString();
Toast.makeText(getApplicationContext(), s, 1500).show();
file.delete();
How can I overcome this problem?
Use getFileStreamPath(FILENAME) to find your file. From the docs:
Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.
Your current working directory.
To help diagnose the problem, use file.getAbsolutePath() to see the full path.
It could also be a permissions problem, if you're trying to delete from another application. If so, you may need to change to MODE_WORLD_WRITEABLE (insecure), or restructure your code so the create and delete are called by the same app.
EDIT: That was mostly incorrect. I didn't realize that openFileOutput didn't use the current working directory.
Use same contents as 'FILENAME' variable in your first snippet in the second snippet while trying to delete.
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Video";
File RootFile = new File(RootDir);
RootFile.mkdir();
FileOutputStream f = new FileOutputStream(new File(RootFile, "Sample.mp4"));
i used this code to save the video files to non-default location. Hope this will be useful to you.By default it is storing in sd card
For each application the Android system creates a "data/data/package of the application" directory.
Files are saved in the "files" folder under this directory
to change the default directory the above code will be used
the default working directory can be displayed using fileobject.getAbsolutePath()

Categories