Create a file in Android with certain permission - android

I'm developing an Android application I have to implement a function that create a folder with different files.
I wish the files in the folders were hidden, and this point is not a problem, but I want assign certain permission to files, for example I need that files are not readable / writable by user but only from application.
Also I wish the files in the folder were deleted if the application was uninstalled.
This is the code that i use to create hidden folder:
File JSONStorage = new File(Environment.getExternalStorageDirectory(), ".BMA");
if (!JSONStorage.exists()) {
if (!JSONStorage.mkdirs()) {
Log.wtf("log: ", "Failed to create directory");
}
}

From official Android documentation:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
This will create file on device internal memory. This file can be read only by application. (Context.MODE_PRIVATE)

Related

How to create hidden directory in android?

I am working on an application where I have created some directory which I am accessing through my application I want to make that directory hidden for security purpose .Such that the user can access them only within the application does not access them outside the application as like through file manager.
Any help is appreciated.
Don't make it duplicate because I search out all the answer, but no one has worked for me.
Just appending a dot before the folder name will not protect it. It is only invisible to the user. It can still be accessed from apps, including file managers and therefore the user. It's just hidden by most file managers by default.
As you want to hide the files for security purposes, you should use Android's internal storage.
From the official Android developer guide:
You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.
Example:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
Android developer guide
You could also encrypt your files and store the encryption key in the android Keystore.
Here is a good answer regarding encryption of files in android.
Official guide regarding the Android Keystore.
Be clear "You want to create directory or folder which is not accessible for other application"(Which is your application folder) Or Create Folder any location but it is hide from your
For First Solution is -
public static File saveFileInAppDirectory(Context context,byte[] inpute, String directoryName,String fileName){
File mypath;
File directory = new File(context.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), directoryName);
if (!directory.mkdirs()) {
directory.mkdir();
}
mypath = new File(directory, fileName);
try {
InputStream is = new ByteArrayInputStream(inpute);
FileOutputStream f = new FileOutputStream(mypath);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.e("SAVE_IMAGE", e.getMessage(), e);
e.printStackTrace();
}
return mypath;
}
It will create Directory of your app folder Path - Android/Data/Data/Your.Package.Name/FolderName/FileName
For second Solution - just change file name
File mypath = new File(directory, "."+fileName);
If you want to achive both than just replace
new File(directory, fileName); with new File(directory, "."+fileName);
just write the directory name followed by a dot(.)
example:
.myDir or .myDir1
so these directories will not be visible through file manager. And while accessing these directories call them using dot(.) only
example:
"/path/to/folder/.myDir/"
same can be done for filename
For Hiding Folder in Android
Name of your folder is MyApplicationFolder then u need to add (.)Dot in front of the folder name like .MyApplicationFolder.
So When the Folder is created then the folder is hidden mode for images,video,etc inside but it will be visible in FileManager.

Android create Folder and detect it

I want to create a folder to save a copy of an image from gallery
to use it from my Directory
I have tried a lot for how to save the image inside the folder and how to use it back.
The folder must be Private Folder so that only my app can access it.
you can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed. For example:
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.
it's take from:
How to create private folder in sdcard
You might want to take a look at the getDir() method that does exactly what you wish to accomplish..

Android app generate

I'm having a little problem with my android app.
My app generates a .html file when a "export button" is pressed.
But I can't see the file in my pc or in the Android's Download app. I can only see it in Astro file manager.
That's how I generate and saved my file .
String string = "Hello World"
String filename = "/sdcard/Download/teste.html";
FileOutputStream outputStream;
try {
File file = new File(filename);
boolean newFile = file.createNewFile();
if(!newFile){ //if the file exists I delete it and generate a new file
file.delete();
newFile=file.createNewFile();
}
Context context=getActivity();
FileOutputStream fOut = new FileOutputStream(file,true);
// Write the string to the file
fOut.write(string.getBytes());
/* ensure that everything is
* really written out and close */
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
I suppose there is a way to visualize this file without the Astro app but I can't find how do this, if someone can help I'll be grateful.
Thanks
First, never hardcode paths. Your path will be wrong on some Android devices. Please use the proper methods on Environment (e.g., getExternalStoragePublicDirectory()) or Context (e.g., getExternalFilesDir()) to get the roots under which you can safely place files.
Beyond that, files that you write to external storage will not be visible to PCs until that file is indexed by MediaScannerConnection, and even then it might require the user to perform some sort of "reload" or "refresh" operation in their file browser to see it.
I have another blog post with more about external storage which may be of use to you.

How to make folders of application in SD card are not accessible by file manager and other applications?.

I am creating two folders to store images of my application in SD card.but these folder are visible in file manger.i want to prevent access of my folder from outside.i am saving images in that two folders.i am saving like this please help me any one.
File sdcard = Environment.getExternalStorageDirectory();
File pictureDir = new File(sdcard, "Image_dir");
if (!pictureDir.exists()) {
pictureDir.mkdirs();
}
// saving the image file in the folder Image_dir
File f = null;
f = new File(pictureDir, file_name);
FileOutputStream fos = new FileOutputStream(f.getAbsolutePath());
Bitmap image;
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
normally adding a . in front of the name of the folder which will exclude it from media scanners. But with a file manager can still find it.
If you are working on Api Level-8 then I suggest to use getExternalFilesDir (String type)
instead of Environment.getExternalStorageDirectory() because there are two benefit using this
all images and data will be automatically deleted when your application uninstall by user
images do not visible in the media application (in Gallery).

How to create a file on Android Internal Storage?

I want to save a file on internal storage into a specific folder. My code is:
File mediaDir = new File("media");
if (!mediaDir.exists()){
mediaDir.createNewFile();
mediaDir.mkdir();
}
File f = new File(getLocalPath());
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(data);
fos.close();
getLocalPath returns /data/data/myPackage/files/media/qmhUZU.jpg but when I want to create the media folder I'm getting the exception "java.io.IOException: Read-only file system". Any ideas how to write my files on internal phone storage in in folder media? Thanks.
You should use ContextWrapper like this:
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);
As always, refer to documentation, ContextWrapper has a lot to offer.
You should create the media dir appended to what getLocalPath() returns.
I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/ or /mnt/sdcard/. Let me explain.
If you execute the following statement:
File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();
It will resolve the path to the root /data/ somewhere higher up in Android.
I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/ without me translating anything on my own.
File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();
A quick fix would be to change your following code:
File f = new File(getLocalPath().replace("/data/data/", "/"));
Hope this helps
Write a file
When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:
getFilesDir()
Returns a File representing an internal directory for your app.
getCacheDir()
Returns a File representing an internal directory for your
app's temporary cache files.
Be sure to delete each file once it is no longer needed and implement a reasonable
size limit for the amount of memory you use at any given time, such as 1MB.
Caution: If the system runs low on storage, it may delete your cache files without warning.
Hi try this it will create directory + file inside it
File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
mediaDir.mkdir();
}
File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();
System.out.println("Your file has been written");

Categories

Resources