Delete an internal save file - Android - java

How do I delete an internal save file dynamically in an Android application? I saved it in the default directory so I don't know the exact file path. Here is the code I used to save my files if that helps any:
public void saveAssignments(){
String saveData = "";
String FILENAME = name.replaceAll(" ", "") + ".txt";
//Context context = getApplicationContext();
Context context = getActivity();
FileOutputStream fos;
for(int i = 0; i < allEds.size(); i++){
saveData = saveData + allEds.get(i).getText().toString() + ", ";
}
try{
fos = context.openFileOutput( FILENAME, Context.MODE_PRIVATE );
try{
fos.write(saveData.getBytes());
fos.close();
//Toast.makeText(context, "Saved as " + FILENAME, 5000).show(); //popup message
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

You can delete file created by using openFileOutput method as:
File file=new File(context.getFilesDir().getAbsolutePath()+"/"+FILENAME);
if(file.exists())file.delete();

You could use method
deleteFile(String filename)
on your context-object.
http://developer.android.com/reference/android/content/Context.html#deleteFile%28java.lang.String%29
Furthermore you could use
String[] fileList ()
to query your files.
http://developer.android.com/reference/android/content/Context.html#fileList%28%29

You should try
getFilesDir() from context to return path or refer to here. Then you can delete it.

Related

Image not overwriting on same name

I'm developing image editor app.. so each time the user have to save the image.
So first i inserted
String savedImageURL = MediaStore.Images.Media.insertImage(
getContentResolver(),
bitmap,
"Bird",
"Image of bird"
);
this code, but it creating new file instead of overwriting.
So i use another method
public String saveImage(String folderName, String imageName) {
String selectedOutputPath = "";
if (isSDCARDMounted()) {
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
// Create a storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("PhotoEditorSDK", "Failed to create directory");
}
}
// Create a media file name
selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName;
Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath);
File file = new File(selectedOutputPath);
try {
FileOutputStream out = new FileOutputStream(file,true);
if (parentView != null) {
parentView.setDrawingCacheEnabled(true);
parentView.getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 80, out);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return selectedOutputPath;
}
But it also didn't work.
Does anyone know about overwrite a bitmap in the same name?
Pass false as 2nd argument, to set append to false, so that you will overwrite the existing file:
FileOutputStream out = new FileOutputStream(file,false);
Check out the constructor documentation:
here is your code:
public String saveImage(String folderName, String imageName) {
String selectedOutputPath = "";
if (isSDCARDMounted()) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
// Create a storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("PhotoEditorSDK", "Failed to create directory");
}
}
// Create a media file name
selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName;
Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath);
File file = new File(selectedOutputPath);
if (file.exists())
{
try {
file.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
file.createNewFile();
FileOutputStream out = new FileOutputStream(file,false);
if (parentView != null) {
parentView.setDrawingCacheEnabled(true);
parentView.getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 80, out);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return selectedOutputPath;
}
I also had this situation, but it turns out that this is not a problem with saving, but with displaying in ImageViev. I used Glide, and it turns out to be stored in the cache when outputting. And I did not change the name and path of the file. That is, I rewrote them. But Glide did not know this. He thought they were the same file. To fix this problem, I added the following
Glide.with(context)
.load(file)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(view)
If you also have this situation and these solutions helped you, I'm glad to this.

Android app creates file but can't find it

I'm having an issue that is preventing me from releasing my app, so maybe you can help. I have this code to create and write to a file:
#Override
public void onClick (View view){
final String memoryString = memory.getText().toString();
File file = new File(getApplicationContext().getFilesDir(), filename);
FileOutputStream fos = new FileOutputStream(file);
if (location != null) {
String s = location.toString() + " " + memoryString;
Log.d(null, s);
if(fos != null) {
Log.d(null, "fos not null");
fos.write(s.getBytes());
} else {
Log.d(null, "Output Stream is null");
}
fos.close();
Log.d(null, "file created!");
}
} catch (IOException e) {
e.printStackTrace();
}
my log is saying that it's creating the file. but when I go to access and read from said file, I get the error here that it doesn't exist:
try {
File memoryFile = new File(filename);
if(memoryFile.exists()){
revealMarkers(memoryFile);
Log.d(null, "revealed");
} else {
Log.d(null, "no file found");
}
} catch (FileNotFoundException ex) {
Log.d(null, "file not found");
}
Please help if you are able, I am very much stuck
Maybe this ?
try {
File memoryFile = new File(getApplicationContext().getFilesDir(), filename);
if(memoryFile.exists()){
revealMarkers(memoryFile);
Log.d(null, "revealed");
}else{Log.d(null, "no file found");}
} catch (FileNotFoundException ex) {
Log.d(null, "file not found");
}
How is it that you created a file with this statement
File file = new File(getApplicationContext().getFilesDir(), filename);
And then try to retrieve the file with this
File memoryFile = new File(filename);
Why can't you use the same statement. How is the second statement supposed to determine the directory containing the file?

How to save a file to a specific spot on the phone

I would like for my app to create a folder on the sd card and save a file in it. This is what I have right now that just saves it in my app data.
File file = new File(context.getExternalFilesDir(""), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
How would I do that?
Alright so I did this. Am I even doing this right?
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "";
File file = new File(fullPath);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
Your best option is to use Environment.getExternalStorageDirectory() to find the root path to use.
However, please note that this is not nessasarily the sd-card, from the docs:
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
Example, just change your first line to be:
File file = new File(Environment.getExternalStorageDirectory(), fileName);
Need a directory?:
File dir = new File(Environment.getExternalStorageDirectory(), "yourdir");
dir.mkDirs();
File file = new File(dir, fileName);
Try this, Create file folder like this
String fullPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Foldername";
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}

Create file in specified directory

Try to create file in specific directory but it shows the error FileNotFound. Why?
Am I using impossible path? I really don't know, but is seems like the code should be working.
String day=/1;
String zn="/zn";
File_name=zn
String root= Environment.getExternalStorageDirectory().toString();
File_path=root+day;
File file1 = new File(File_path,File_name);
file1.mkdirs();
if(!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream fos= new FileOutputStream(file1);
String l,d,p;
l = lessnum.getText().toString();
d = desc.getText().toString();
p = place.getText().toString();
fos.write(l.getBytes());
fos.write(d.getBytes());
fos.write(p.getBytes());
fos.close();
Change your code as for creating a file on sdcard
String root= Environment.getExternalStorageDirectory().getAbsolutePath();
String File_name = "File_name.Any_file_Extension(like txt,png etc)";
File file1 = new File(root+ File.separator + File_name);
if(!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
In current you you are also missing file Extension with file name so change String zn as zn="/zn.txt";
and make sure you have added Sd card permission in AndroidManifest.xml :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
First you make a directory
String root= Environment.getExternalStorageDirectory().toString();
String dirName =
root+ "abc/123/xy";
File newFile = new File(dirName);
newFile.mkdirs();
then you create a file inside that directory
String testFile = "test.txt";
File file1 = new File(dirName,testFile);
if(!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
then do your file writing operations
try { OutputStream fos= new FileOutputStream(file1);
String l,d,p;
l = lessnum.getText().toString();
d = desc.getText().toString();
p = place.getText().toString();
os.write(l.getBytes());
fos.write(d.getBytes());
fos.write(p.getBytes());
fos.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think this will help you...
Thanks...
you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And check http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29
String root= Environment.getExternalStorageDirectory().toString();
String dirName =
root+ "abc/123/xy";
File newFile = new File(dirName);
newFile.mkdirs();
String testFile = "test.txt";
File file1 = new File(dirName,testFile);
if(!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And and <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
on manifest file...
Thanks...
Here is your latest attempt:
File_path = root + File.separator + day;
File f_dir = new File(File_path);
f_dir.mkdirs();
File file1 = new File(f_dir, File_name);
if (!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream fos= new FileOutputStream(file1);
If you showed us the complete stacktrace and error message it would be easier to figure out what is going wrong, but I can think of a couple of possibilities:
You are not checking the value returned by f_dir.mkdirs(), and it could well be returning false to indicate that the directory path was not created. This could mean that:
The directory already existed.
Something existed but it wasn't a directory.
Some part of the directory path could not be created ... for one of a number of possible reasons.
The file1.exists() call will return true if anything exists with that pathname given by the object. The fact that something exists doesn't necessarily mean that you can open it for writing:
It could be a directory.
It could be a file that the application doesn't have write permissions for.
It could be a file on a read-only file system.
And a few other things.
If I was writing this, I'd write it something like this:
File dir = new File(new File(root), day);
if (!dir.exists()) {
if (!dir.mkdirs()) {
System.err.println("Cannot create directories");
return;
}
}
File file1 = new File(dir, fileName);
try (OutputStream fos= new FileOutputStream(file1)) {
...
} catch (FileNotFoundException ex) {
System.err.println("Cannot open file: " + ex.getMessage());
}
I only attempt to create the directory if required ... and check that the creation succeeded.
Then I simply attempt to open the file to write to it. If the file doesn't exist it will be created. If it cannot be created, then the FileNotFoundException message should explain why.
Notice that I've also corrected the style errors you made in your choice of variable names.

Where will be a file created in android if I do it like this

This function creates a file but I can't figure out where is the file created and if someone has a solution to create a file in a particular directory from the external storage is very welcomed :) thanks a lot
private void writeFileToInternalStorage() {
String eol = System.getProperty("line.separator");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("myfile", MODE_WORLD_WRITEABLE)));
writer.write("This is a test1." + eol);
writer.write("This is a test2." + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
for query
Where will be a file created
it will create in Internal Storage as function name said and that will be like
/data/data/yourApp_package_as_in_manifest/ (can see in DDMS)
for query
if someone has a solution to create a file in a particular directory
from the external storage is very welcomed
as per link Write a file in external storage in Android
.........
** Method to check whether external media available and writable. This is adapted from
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */
private void checkExternalMedia(){
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable="
+mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}
/** Method to write ascii text characters to file on SD card. Note that you must add a
WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
a FileNotFound Exception because you won't have write permission. */
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
// See https://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to "+file);
}
and also add a WRITE_EXTERNAL_STORAGE permission to the manifest
It will be created on internal folder: /data/data/com.package.name/ You cannot access that folder using file browser.
If you want to easily access the file you can try to create it on SD card:
/*...*/
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = baseDir + "/"+ "myFile.txt";
FileOutputStream writer = null;
try {
writer = new FileOutputStream(fileName);
writer.write("This is a test1." + eol);
/*...*/

Categories