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?
Related
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.
This question already has answers here:
Java 'file.delete()' Is not Deleting Specified File
(8 answers)
Closed 5 years ago.
Here is my code of deleting the pdf file
try {
File file = new File(docObjectId + ".pdf");
file.setWritable(true);
System.out.println(file.length());
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
It goes to the else part of the code.
PDF file is in project root folder and I am able to delete it manually. Scratching my head now.
Here is complete method. It might be due to some other reason
public Response getContractDocument(#PathParam("docid") String docObjectId) throws Exception {
DocumentumService documentumService = new DocumentumService(documentumConfigUtil);
DocumentumDocumentBean docDocumentBean = documentumService.getContractDocContent(docObjectId, true);
FileInputStream fileInputStream;
fileInputStream = new FileInputStream(docDocumentBean.getDocFile());
compressPdf(fileInputStream,docObjectId + ".pdf");
fileInputStream = new FileInputStream(docObjectId + ".pdf");
ResponseBuilder responseBuilder = Response.ok((Object) fileInputStream);
try {
File file = new File(docObjectId + ".pdf");
System.out.println(file.getAbsolutePath());
file.setWritable(true);
System.out.println(file.length());
File d = new File(file.getAbsolutePath());
if (d.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch(Exception e) {
e.printStackTrace();
}
return responseBuilder.build();
}
My experience is with windows. The reason that a file won't delete is always the same. Some object has a connection to the file and is holding it open. In this case, it looks like it might be fileInputStream.
Try this before you attempt to delete:
fileInputStream.close();
Change if(file.delete) to
try {
file.delete();
System.out.println("file deleted");
} catch(IOException e) {
System.out.println("file not deleted");
}
The exception may not be accurate.
First, check if the file exist or not and then delete it.
Kindly use the below code. Its working fine and is very clear approach for deletion. I hope it would help.
public static void main(String[] args) {
try{
File file = new File("C:/Users/Tehmina Yaseen/Documents/NetBeansProjects/FileDeletion/src/filedeletion/Myfile.pdf");
if (file.exists()) {
file.delete();
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the output:
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 copy an android db file from my application folder to another one on SD card. And from DDMS file explorer i can notice that the copied file size is 0. This is my code bellow.
public boolean copyDBFile(){
File dbFile =new File(Environment.getDataDirectory() + DB_PATH);
File exportDir = new File(Environment.getExternalStorageDirectory()
+ "/BACKUP_DIR");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
copyFile(dbFile, file);
return true;
} catch (IOException e) {
return false;
}
}
public void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
Is it a permission issue? Thanks for help.
#piyush
Thanks for the try/catch notice. I found the error after adding a log trace in boolean copyDBFile() method at catch block.
public boolean copyDBFile(){
File dbFile =new File(Environment.getDataDirectory() + DB_PATH);
File exportDir = new File(Environment.getExternalStorageDirectory()
+ "/BACKUP_DIR");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
copyFile(dbFile, file);
return true;
} catch (IOException e) {
Log.e("Sarelo", "Error creating file", e);
return false;
}
}
My DB_PATH was already set to /data/data/package/databases/data.db and added to Environment.getDataDirectory() the dbFile result to /data/data/data/package/databases/data.db
That's the big mistake! Thanks all for help :)
try using outChannel.force(true); before using the transferTo(...);