I'm trying to save file 0_0.xml in cache. So I do it like this
String fileName = "0_0.xml"
File file = new File(context.getCacheDir(), fileName);
if (file.exists()) {
...
} else {
file = File.createTempFile(fileName, null, context.getCacheDir());
FileOutputStream fos = new FileOutputStream(file);
try {
fos.write("some_string".getBytes());
} finally {
fos.close();
}
}
I've run my application for several times and wondered that it always could not find this file (if not file.exists() I write it like I described above) so it created new one each time. After that I listed all files in my cache and got something like this:
The question is why does my file change it's name and how can I access to it?
You call File.createTempFile to create the file. createTempFile() will compute a new, unique, name for your temporary file to avoid collisions with other operations that also need a temporary file.
If you want to keep the file and find it again, don't use createTempFile() to generate new and unique names. Instead use the same object (file) that you used when you checked to see if it existed.
Related
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.
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.
In Android, I want to create a pointer that points to already existing file by way of its filepath.
For example, my pseudo-code:
String path = "file/directory/filename";
File ptr = File's pointed to by the path
The Android documentation only provides methods with which one can create a new file through a file path, but I just want a File object that only points to an already existing File.
How do I do that?
Use:
String path = "file/directory/filename";
File ptr = new File(path);
// check If file exists.
if(ptr.exists()) {
// Your code Here if file exists
}
File f = new File(path);
f points to a virtual file , if the file doesnt exist, writing anything to it, will either create it or cause a system crash , depending on the type of content you are writing to it.
deleting a file that doesnt exist will also fail, so any operation with files must be encapsulated with try catch for IOException
see http://developer.android.com/reference/java/io/File.html
also on android's new Kitkat you explicity have to request the permission to READ_EXTRANL_STORAGE if you want to read, and WRITE_EXTERNAL_STORAGE if you want to write
Android provides many options for storing data persistently on the device. I have opted for internal storage, so please don't make suggestions for storing on an SD card. (I've seen too many questions about internal storage have answers for SD cards!!)
I would like to create subdirectories in my application's internal storage directory. I followed this SO answer, reproduced below.
File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.
Unfortunately, that's creating subdirectories with "app_" prefixes. So, from the example, the subdirectory looks like "app_mydir" (not ideal).
The answer to this SO question suggests that you can get rid of the "app_" prefix this way:
m_applicationDir = new File(this.getFilesDir() + "");
m_picturesDir = new File(m_applicationDir + "/mydir");
But I want to write a zip to something like /data/data/com.mypackages/files/mydir/the.zip.
So, in the end, my code looks like this:
File appDir = new File(getApplicationContext().getFilesDir() + "");
File subDir = new File(appDir + "/subDir");
File outFile = new File(subDir, "/creative.zip");
But, this is creating another error: "File does not exist" when I try this:
FileOutputStream fileStream = new FileOutputStream(outFile);
How can I (1) create a subdirectory without the "app_" prefix and (2) write a zip into it?
Also, if my first demand isn't reasonable, tell me why in the comments! I'm sure "app_" prefix has some meaning that escapes me atm.
Did you create the directories?
File appDir = getApplicationContext().getFilesDir();
File subDir = new File(appDir, "subDir");
if( !subDir.exists() )
subDir.mkdir();
File outFile = new File(subDir, "creative.zip");
Note that you shouldn't use / anywhere in your app, just in case it changes. If you do want to create your own paths, use File.separator.
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");