Creating Folder in Internal memory - android

I am unable to get the methods for creating folder in Internal Memory,
i gone through few conversations in Android create folders in Internal Memory and Problem facing in reading file from Internal memory of android. But still i am unable to meet my requirement.
My requirement is , I want to create a folder in Internal Memory, there i want to Store one video.
Thankyou you very much in advance for valuable feedbacks.

try the below
File mydir = context.getDir("users", Context.MODE_PRIVATE); //Creating an internal dir;
if (!mydir.exists())
{
mydir.mkdirs();
}

Here is the code which I am using for creating files in internal memory :
File myDir = context.getFilesDir();
// Documents Path
String documents = "documents/data";
File documentsFolder = new File(myDir, documents);
documentsFolder.mkdirs(); // this line creates data folder at documents directory
String publicC = "documents/public/api." + server;
File publicFolder = new File(myDir, publicC);
publicFolder.mkdirs(); // and this line creates public/api.myservername folder in internal memory

To create directory on phone primary storage memory (generally internal memory) you should use following code. Please note that ExternalStorage in Environment.getExternalStorageDirectory() does not necessarily refers to sdcard, it returns phone primary storage memory
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyDirName");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("App", "failed to create directory");
return null;
}
}
Directory created using this code will be visible to phone user. The other method (as in accepted answer) creates directory in location (/data/data/package.name/app_MyDirName), hence normal phone user will not be able to access it easily and so you should not use it to store video/photo etc.
You will need permissions, in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
File direct = new File(Environment.getExternalStorageDirectory()+"/folder_name");
if(!direct.exists()) {
if(direct.mkdir()); //directory is created;
}

There is a "cacheDirectory" in your "data/package_name" directory.
If you want to store something in that cache memory,
File cacheDir = new File(this.getCacheDir(), "temp");
if (!cacheDir.exists())
cacheDir.mkdir();
where this is context.

try {
File cashDir = new File(dir.getCanonicalPath(),"folder");
if(!(cashDir.exists())) cashDir.mkdirs();
} catch (IOException e) {
e.printStackTrace();
}

Related

This code creating the folder in INTERNAL STORAGE Everytime ,I need to create folder in my SDCARD

Why does this code only create a new folder in the internal storage and not create the folder on the SD Card.
Thanks
Code:
File direct = new File(Environment.getExternalStorageDirectory()+"/Akshay");
if(!direct.exists()) {
if(direct.mkdir()); //directory is created;
}
Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Try this :
File f = new File(Environment.getExternalStorageDirectory(), 'Akshay');
if (!f.exists()) {
f.mkdirs();
}

a way to store the image folder of my application with restrictions

I would like to know if there is a way to store the image file of my application to the mobile external storage of the mobile phone but that the galery application does not display the images contained in this folder.
Add ".nomedia" file.
Save your files to a folder that starts with ".", e.g., /sdcard/.myimages/
You can create .nomedia file using this code:
String NOMEDIA=".nomedia";
File Folder = new File(Environment.getExternalStorageDirectory() + "/mydir");
if(Folder.mkdir()) {
nomediaFile = new File(Environment.getExternalStorageDirectory() + "/mydir/"+ NOMEDIA);
if(!nomediaFile.exists()){
nomediaFile.createNewFile();
}
}
OR
Add storage permission in your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
private void hideMyFile(String original_name,String new_name)
{
try
{
File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,original_name);//abc.png
File to = new File(sdcard,new_name);//abc
from.renameTo(to);
}
catch (Exception e)
{
e.printStackTrace();
}
}
So call this function hideMyFile() and pass two parameter and it will rename the file with no extension in this way those image will not appear in gallery

How can we create a folder of app in device storage in Android?

I'm using code in comment to save a file in directory folder. This code is working properly with mobile phone having sd card.
But if I use it with mobile phone not having sd card it is giving IO exception.
How can I create a folder like whatsapp has in device storage root to save images etc but I want a folder of application name to save .csv files in my device storage root.
First make sure you have added Storage Permissions inside Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
If you want to create folder inside ExternalDirectory
File f = new File(Environment.getExternalStorageDirectory()+"/foldername");
if(!f.exists()) f.mkdir();
If you want to create file inside internal storage
File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal directory;
File fileWithinMyDir = new File(mydir, "myfile");
FileOutputStream out = new FileOutputStream(fileWithinMyDir);
You can create directory in internal storage and external storage as Follows.
//check whether Sdcard present or not
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent)
{
// yes SD-card is present
String directory = "/your Directory name or app name ";
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + directory;
File dir = new File(path);
if(!dir.exists()) //check if not created then create the firectory
dir.mkdirs();
//add your files in directory as follows
File file = new File(dir, filename);
}
else
{
// create folder in internal memory
File mydir = context.getDir(directory, Context.MODE_PRIVATE); //Creating an internal directry
if(!mydir.exists()) //check if not created then create the firectory
mydir.mkdirs();
//add your files in directory as follows
File file = new File(mydir, filename);
I hope it will work for you

How to Store a File in our sd card that we have inserted

I am trying to save a file in my External SDcard but the file is getting stored in internal storage. How to store the file in the SDcard inserted
mr = new MediaRecorder();
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
Log.e("aa","sss");
cameraFolder = new File(android.os.Environment.getExternalStorageDirectory(), "Recorder");
} else {
cameraFolder= getDir("Recorder",MODE_PRIVATE);
}
if(!cameraFolder.exists()) {
cameraFolder.mkdir();
}
fname = cameraFolder + "/myrec1.MPEG_4";
There is already a similar question here, you can also find more detailed information on the android docs
As suggested in a comment below I'll improve this answer.
In order to save a file to a specific position in your SD card you need to create a File object which points to that position:
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/your/file/directory");
dir.mkdirs();
File file = new File(dir, "filename");
and then use a FileOutputStream to write the content.
Remember that you need to add the required permission in the manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

EACCESS Permission denied in Android

While writing file in External SD card I am getting an error EACCESS permission denied. I have set the permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
But the when I read the file I am successfully able to read it but not able to write the file. The code that I am using for writing the file in SD card is:
String path="mnt/extsd/Test";
try{
File myFile = new File(path, "Hello.txt"); //device.txt
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+myFile.getPath(),Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
System.out.println("Hello"+e.getMessage());
}
}
The path for the external storage card is mnt/extsd/. Thats why I am not able to use Environment.getExternalStorageDirectory().getAbsolutePath() which is giving me a path mnt/sdcard and this path is for internal storage path in my tablet. Please suggest why this is so n how can I resolve this
As I remember Android got a partial multi-storage support since Honeycomb, and the primary storage (the one you get from Environment.getExternalStorageDirectory, usually part of the internal eMMC card) is still protected by the permission WRITE_EXTERNAL_STORAGE, but the secondary storages (like the real removable SD card) are protected by a new permission android.permission.WRITE_MEDIA_STORAGE, and the protection level is signatureOrSystem, see also the discussion in this article.
If this is the case then it seems impossible for an normal app to write anything to the real sdcard without a platform signature...
From API level 19, Google has added API.
Context.getExternalFilesDirs()
Context.getExternalCacheDirs()
Context.getObbDirs()
Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions. Restricting writes in this way ensures the system can clean up files when applications are uninstalled.
Following is approach to get application specific directory on external SD card with absolute paths.
Context _context = this.getApplicationContext();
File fileList2[] = _context.getExternalFilesDirs(Environment.DIRECTORY_DOWNLOADS);
if(fileList2.length == 1) {
Log.d(TAG, "external device is not mounted.");
return;
} else {
Log.d(TAG, "external device is mounted.");
File extFile = fileList2[1];
String absPath = extFile.getAbsolutePath();
Log.d(TAG, "external device download : "+absPath);
appPath = absPath.split("Download")[0];
Log.d(TAG, "external device app path: "+appPath);
File file = new File(appPath, "DemoFile.png");
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.ic_launcher);
Log.d(TAG, "file bytes : "+is.available());
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.d("ExternalStorage", "Error writing " + file, e);
}
}
Log output from above looks like:
context.getExternalFilesDirs() : /storage/extSdCard/Android/data/com.example.remote.services/files/Download
external device is mounted.
external device download : /storage/extSdCard/Android/data/com.example.remote.services/files/Download
external device app path: /storage/extSdCard/Android/data/com.example.remote.services/files/
I solved this problem by removing the android:maxSdkVersion="18" in uses-permission
in manifest file.
I.e. use this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
instead of:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
Check if user is having external storage permission or not. If not then use cache dir for saving the file.
final boolean extStoragePermission = ContextCompat.checkSelfPermission(
context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED;
if (extStoragePermission &&
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) {
parentFile = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
}
else{
parentFile = new File(context.getCacheDir(), Environment.DIRECTORY_PICTURES);
}

Categories

Resources