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.
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 have written a method which creates a file and writes data to the file and stores in the internal storage. When I get the absolute path or path of the file [I have added log messages to experiment with the operations on the File], it shows me that the file is getting created under the root directory and its under the /data/data/mypackagename/files/filename.txt. Nevertheless, I could find these folders on the DDMS where I could find the file which has been created by the method which I have written. But I am unable to open that file too as I don't have permissions.
When I look at my Android device, I can't find these directories. I looked up on stack overflow and some have answered that the /data/data folders in the internal storage are hidden and to access them I have to root the device which I don't want to do.
Next approach: There is a folder called as MyFiles on the android device [I am using Galaxy Tab 4 running Android 4.4 for testing]. Under this folder there is Device Storage directory which has various folders like Documents, Pictures, Music, Ringtones, Android, etc, etc.. So, the apps like camera, spread sheet apps, are able to write or save pictures into the pictures folder or txt files in the documents folder. Similarly, how could I write the file which I am creating in the function to the Documents folder or any other folder which could be accessible over the device. Please help me how could I do it, any help is appreciated.
The following is the code which I have written:
public void addLog(String power_level){
// creates a logFile in the root directory of the internal storage of the application.
// If the file does not exists, then it is created.
Log.d("AppendPower", "In addLog method");
//File logFile = new File(((Context)this).getFilesDir(), "logFile.txt");
File logFile = new File(getFilesDir(), "logFile.txt");
Log.d("FilesDir Path", getFilesDir().getAbsolutePath());
Log.d("FilesDir Name", getFilesDir().getName());
Log.d("Path on Android", logFile.getPath());
Log.d("Absolute Path on Android", logFile.getAbsolutePath());
Log.d("Parent", logFile.getParent());
if(!logFile.exists()){
try{
logFile.createNewFile();
}catch(IOException io){
io.printStackTrace();
}
}
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true));
writer.write("Battery level reading");
writer.append(power_level);
Log.d("Power_Level in try", power_level);
writer.newLine();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
As you have figured out writing to root directories in Android is impossible unless you root the device. Thats why even some apps in Play-store asking for root permissions before installing the app. Rooting will void your warranty so i don't recommend it if you don't have serious requirement.
Other than root directories you can access any folder which are visible in your Android file manager.
Below is how you can write into sd with some data - Taken from : https://stackoverflow.com/a/8152217/830719
Use these code you can write a text file in SDCard along with you need to set permission in android manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
this is the code :
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}
.
1) If your purpose is debugging, you may just write to the /sdcard/. It always works.
2) Again, if your purpose is debugging, you may try to set read permissions on your app's directories. A while ago it worked for me on some Android devices (but did not work on at least one device).
Add this permission in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Then use this shortest recipe:
try
{
FileOutputStream fos =
openFileOutput("myfile.txt", getApplicationContext().MODE_PRIVATE);
fos.write("my text".getBytes());
fos.close();
}
catch (Exception exception)
{
// Do something, not just logging
}
It will be saved in "/data/data/my.package.name/files/" path.
Having a problem writing out to a file, this code is taken directly from the android developer page and then tweaked a bit by me. Is there something i am missing? Quite new to Android development so sorry if it's something blatantly obvious.
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FileOutputStream outputStream;
String data = "hello";
File fileDir = new File("data.txt");
if (!fileDir.exists())
fileDir.mkdirs();
try {
outputStream = openFileOutput("data.txt",Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
Basically, your problem is that you are trying to do it twice, once in a way that won't work, and once in a way that will, but hides the result.
File fileDir = new File("data.txt");
if (!fileDir.exists())
fileDir.mkdirs();
This would create a Java File object connected to a hypothetical file called "data.txt" located in the current working directory, which for an Android app is the root directory of the device - a place you most definitely are not allowed to write to. However, this may not obviously cause any errors, as the root directory exists so mkdirs() will do nothing, and you only create a File object, you don't actually try to create a file on "disk". Effectively this code does nothing for you - get rid of it.
Next you try something basically workable:
try {
outputStream = openFileOutput("data.txt",Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
openFileOutput() is a method of a Context (Activity or Service) which creates an output stream to write to an actual file located in the private internal storage area of your app. This is all fine and good, and normally a good choice for storing typical data. However, it is not a place that you will be able to examine when running a release app on a secured device, as neither ADB based tools nor Mass Storage or MTP access over USB have rights to it. So it's entirely possible that this code worked, but you had no way to discover that fact. If you are on an emulator, you can access this location with ADB or the DDMS browser, and if your apk is a debug one, you can use the run-as command line tool in the shell.
If you want to share the data, you might consider putting it on the External Storage instead.
I am in need to create a text file where the input is taken from the user.
I am trying to save the txt file in a folder(folder should be created even if it is not there)
My code is as follows,
FileOutputStream fileos = null;
if (FreeMemory() != 0) {
FileOutputStream fos=null;
try {
File path=new File(getFilesDir(),"sri");
if(!path.exists()){
path.mkdir();
}
File mypath=new File(path,"myfile.txt");
if (!mypath.exists()) {
fos = new FileOutputStream( mypath);
String text="Write Hii";
fos.write(text.getBytes());
fos.close();
}
}catch(Exception e){
}
}
The "path" variable gives this path: "/data/data/com.example.gm/files/sri"
I navigated to this path in my device: Android-->Data-->com.example.gm-->files-->
but the folder "sri" is not created and even the file also. Am I navigating to th ecorrect path ? I am not able to find out the file in the device.
I searched for the folder by installing "Astro File Manager" app too. But, couldn't find it. I am not getting any Exception when writing to the folder. The code must be correct. But where is the folder and file? Please anyone help me in solving this.
I want to save the txt file in internal memory of my device.
Whats wrong with my code? Please suggest me the solution.
I have gone through many trails and finally approached stackoverflow.
Thanks for any help!!
The data in the internal storage is not accessible out side the application owning it, so any third party application like file browser or Astro File Manager will not be able to see the files. The application with root access will only be able to access the files in the internal memory. I believe you should programmatically verify if the file is created. getFilesDir() will give the internal memory location allocated to that app.
Have you give the permission in manifiest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
First of all, I want to know if making a file without extension is okay. For example, making a file with ".txt" extendsion will make it a txt file on a computer, but I don't know it matters in android. And I noticed that when working on eclipse, I could deleted a fild with the extensions but couldn't delete a file without a extension.
I want my program to delete a file in the internal storage (com.name.application folder) but it's not working for me.
I make a file with
FileOutputStream fos = openFileOutput(FileName, MODE_PRIVATE);
write with
bos = new BufferedOutpuStream(openFileOutput(FileName,Context.MODE_APPEND)
bos.write(newVocabFile.getBytes());
and I want to delete with
FILE file = new File(fileName);
fild.delete();
I did researches on google and applied different methods to my codes, but every method did not work for me. Because .delete() does not work properly, .exist() does not work either. I tired making the mile with and without extension but both ways did not work either.
I really need to get through this in order to finish my application. Please help me
You have a typo on this line
FILE file = new File(fileName);
fild.delete();
It should be
File file = new File(fileName);
file.delete();