How to check if file name already exists? - java

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....

Related

problem when upload file in play framework

I tried uploading a file, and placed the file in the "public / images" directory and it worked, but the file I uploaded was zero in size and certainly couldn't be opened
public Result upload() throws IOException {
Http.MultipartFormData<File> requestBody = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart<File> profile_pic = requestBody.getFile("profile_pic");
String dirPath = "public/images/";
if(profile_pic != null) {
String name = profile_pic.getFilename();
File file = profile_pic.getFile();
System.out.println(file);
File theDir = new File(dirPath);
if (!theDir.exists()) {
boolean result = false;
try {
theDir.mkdirs();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
try {
File filex = new File(dirPath + name.toLowerCase());
filex.createNewFile();
file.renameTo(filex);
}catch (Exception e) {
// TODO: handle exception
}
return ok("File uploaded ");
}else {
return badRequest("Eroor");
}
}
this is my file after upload
I think creating a new file and renaming your old file to that name may cause trouble. I would recommend using the move method, see docs here.
Does your System.out.println(file); print what looks like a normal png file?

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?

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