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.
Related
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.
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();
}
I have a voice recording app and I'm trying to implement a feature that checks if the recorded file with a certain name already exists. If a user types in a file name that already exists, an alert dialog should be shown.
All file names are stored in a .txt file on the device.
My current code:
try {
BufferedReader br = new BufferedReader(new FileReader(txtFilePath));
String line = null;
while ((line = br.readLine()) != null) {
if (line.equals(input.getText().toString())) {
nameAlreadyExists();
}
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
newFileName = input.getText();
from = new File(appDirectory, beforeRename);
to = new File(appDirectory, newFileName + ".mp3");
from.renameTo(to);
writeToFile(input);
toast.show();
This code only works halfway as it should. It does successfully check if the file name already exists. If the file name doesn't yet exist, it will work fine. But if the file name already exists, then the user will get the "nameAlreadyExists()" alert dialog but the file will still be added and overwritten. How do I make my code stop at "nameAlreadyExists()"?
I solved the problem with the following code:
File newFile = new File(appDirectory, input.getText().toString() + ".mp3");
if (newFile.exists())
{
nameAlreadyExists();
}
else
{
newFileName = input.getText();
from = new File (appDirectory, beforeRename);
to = new File (appDirectory, newFileName + ".mp3");
from.renameTo(to);
writeToFile(input);
toast.show();
}
The File class provides the exists() method, which returns true if the file exists.
File f = new File(newFileName);
if(f.exists()) { /* show alert */ }
You can easy write return; to get out from the function (if that is the function). Or use
if(f.exists() /* f is a File object */ ) /* That is a bool, returns true if file exists */
statement, to check if file exists and then do correct things.
Below is the code i used to do the task,
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"My_Folder");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("My_Folder", "failed to create directory");
return null;
}
}
I think you are missing some flag to fork your code in case the file does exist:
boolean fileExists = false;
try {
BufferedReader br = new BufferedReader(new FileReader(txtFilePath));
String line = null;
while ((line = br.readLine()) != null) {
if (line.equals(input.getText().toString())) {
fileExists = true;
nameAlreadyExists();
}
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
if(!fileExists)
{
newFileName = input.getText();
from = new File(appDirectory, beforeRename);
to = new File(appDirectory, newFileName + ".mp3");
from.renameTo(to);
writeToFile(input);
toast.show();
}
and feel free to use the exists() function of File as above....
I'm trying to create a file on the SD on my device. This worked a week ago, but now it isn't, and I don't understand why.
The Logcat prints:
java.io.FileNotFoundException ...pathtofile... (no such file or directory)
So, the file is not being created. I have the correct permissions on the android manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
I create the file this way:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
base = Environment.getExternalStorageDirectory().getAbsolutePath();
}
String fname = File.separator +"VID_"+ timeStamp + ".3gp";
mediaFile = new File(base+fname);
Then I check if it exists:
if(mediaFile.exists()){
Log.v("mediaFile","ex");
}else{
Log.v("mediaFile","no ex");
}
And the log says that IT DOESN'T EXIST. I also have tried with file.createNewFile() and it doesn't work.
So, a week ago it was working, now it doesn't work, it could be a problem with the SD card ???? Could it be some type of BUG!!!????
Thanks
EDIT: More Code
The function where the file is created is :
private static File getOutputMediaFile()
Called from:
private static Uri getOutputMediaFileUri(){
return Uri.fromFile(getOutputMediaFile());
}
And setted to mediarecorder output as:
vMediaRecorder.setOutputFile(getOutputMediaFileUri().toString());
So, when I do mediarecorder.prepare():
try {
vMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.v("RELEASE VIDREC1",e.toString());
releaseMediaRecorder();
return false;
} **catch (IOException e) {
Log.v("RELEASE VIDREC2",e.toString());
releaseMediaRecorder();
return false;**
}
The bold catch is the one that runs, and prints:
java.io.FileNotFoundException ...pathtofile... (no such file or directory)
just try this
String fname = "VID_"+ timeStamp + ".3gp";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
mediaFile = new File(android.os.Environment.getExternalStorageDirectory(),fname);
if(!mediaFile.exists())
{
mediaFile.createNewFile();
}
}
if(mediaFile.exists()){
Log.v("mediaFile","ex");
}else{
Log.v("mediaFile","no ex");
}
You merely create the object mediaFile, not the actual file. Use this:
if(!f.exists()){
f.createNewFile();
}
I tried this, for me it works.
final String filename = "file.3gp";
final String path = Environment.getExternalStorageDirectory() + "/" + filename;
File outputfile = new File(path);
if (!outputfile.exists()) {
try {
outputfile.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
}
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outputfile.toString());
try {
recorder.prepare();
recorder.start();
/*recorder.stop();
recorder.reset();
recorder.release();*/
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Try and see whether or not it works. If not, can you add the full code of getOutputMediaFile()?
My answer here:
First open the path, then add the file:
String dir = Environment.getExternalStorageDirectory(); // getAbsolutePath is not requried
File path = new File(dir);
File root = new File(path, "VID_"+ timeStamp + ".3gp";);
Thanks for your help, I've solved the problem using old code. It is strange because the "file saving" part has no modification. Thanks for all guys, kinda.
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);
/*...*/