File Not Found exception: (file exists) - after manually deleting it - java

I've stumbled upon an issue that has been puzzling me. I'm writing an app that creates mp3 files on the external storage. The thing is, if I manually go to the created directory on the phone and delete the file, whenever I try to the create the same file it throws this error:
java.io.FileNotFoundException: /storage/emulated/0/Ringtones/sound1.mp3: open failed: EEXIST (File exists)
Selecting other sounds to be created works just fine, but after I manually delete them they can't be created again due to that issue.
I've already tried deleting the file right after indicating the path and before FileOutputStream but didn't work.
Any tips?
Cheers.

You need to acknowledge the media database before trying to create another copy of the same file. So you need to call this before copying:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(folder path in which your file was)));
Edit: The above answer is deprecated! Please use the following method:
File file = new File(outputPath + fileName);
String filePath = file.toString();
String mimeType = "video/mp4";
MediaScannerConnection.scanFile(this, new String[]{filePath}, new String[]{mimeType}, null);
Example of outputPath and fileName:
String outputPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "My App Name") + "/";
String fileName = "break dance" + ".mp4";
So the File file should be the path of the media you want to update either because it's just deleted or it's newly added, to be visible in Gallery.

Found the answer, following user blackapps' tip. I also changed the directory, as I was using a deprecated reference. Now it is working as intended for sdk 30.

Related

How to check if a file retrieved from the ftp site exists in the local folder in java using talend?

I am using FtpGet to extract or retrieve a file from the ftp and loading into the database and before that i am storing in a local folder.
So before i use tfilecopy to the local Folder i would like to perform a check wherein if the file already exists in the local folder skip or ignore the next steps,if they dont exist then only write (tfilecopy) to the local folder.
So basically i want to iterate through the list of files in the local folder based on the one i am retrieving using
GlobalMap variables:dynamically and check if that file exists or not amongst the list of all the other files in that folder and perform the action.
I Have created this in talend,i could either check the database to see if the file exists or directly check the local folder where there is a copy of the ftp files(if the same file already exists) skip the process.
Only if it does not exist write to the local folder.
Which is the best approach either to scan it in the internal folders(although there maybe sub-folders as well) by writing a tjava code
Or use database script to query and only if the filename does not exist in the table,copy that file onto a target folder and write to a db table.
So primarily i am iterating through the current file from tfilelist3 and checking if they exist in tfilelist2 component using TJAVA and tfilecopy only if the file retrieved does not exist in tfilelist_2
TJAVA:
String path =((String)globalMap.get("tFileList_2_CURRENT_FILEDIRECTORY"));
System.out.println("PRINTING PATH in string: " +path);
Path filepath=Paths.get(path);
System.out.println("PRINTING PATH in PATH: " +filepath);
String fileName =((String)globalMap.get("tFileList_3_CURRENT_FILE"));
System.out.println("PRINTING FILENAME IN STRING: " +fileName);
File file = new File(fileName);
System.out.println("File is " +file);
//File f = new File(path);
if(file.exists())
{
System.out.println("Filename: "+file); //+ path.toString());
System.out.println("Exist in location!");
// System.out.println("File EXIST " +f);
} else
{
System.out.println("Filename: "+file); //+ path.toString());
System.out.println("Does not exist in location!");
}
I kinda made it little complex and i am lost now,would be great if someone could fix the remaining part and make it work,i cant seem to find a way through this maze now !
I had tried different versions and none of the seem to produce the result that i am looking for?
So file.exists() only checks for the specific file in the current directory,so what if i need to check in a different directory,how do i pass the arguments?
Approach 2 :
You can create a java routine eg:
findFile("fileName","FilePath")
Invoke the routine for each file by passing the fileName and filePath as parameters.
Did you check tFileExist component ? It seems that it could be useful (only parameter is folder+filename you want to check ).

Save a binary file in the same folder for every PC

I'm making a game that saves information into a binary file so that I can start at the point I left the game on the next use.
My problem is that it works fine on my PC because I chose a path that already existed to save the file, but once I run the game on another PC, I got an error saying the path of the file is invalid (because i doesn't exist yet, obviously).
Basically I'm using the File class to create the file and then the ObjectOutputStream and ObjectInputStream to read/write info.
Sorry for the noob question, I'm still pretty new to using files.
You must first check if the directory exists and if it does not exist then you must create it.
String folderPath = System.getProperty("user.home") + System.getProperty("file.separator") + "MyFolder";
File folder = new File(folderPath);
if(!folder.exists())
{
folder.mkdirs();
}
File saveFile = new File(folderPath, "fileName.ext");
Please note that the mkdirs() method is more useful in this case instead of the mkdir() method as it will create all non existing parent folders.
Hope this helps. Good luck and have fun programming!
Cheers,
Lofty
You are looking for File mkdirs()
Which will create all the directories necessary that are named in your path.
For example:
File dirs= new File("/this/path/does/not/exist/yet");
dirs.mkdir();
File file = new File(dirs, "myFile.txt");
Take in consideration that it may fail, due to proper file permissions.
My solution has been create a subdirectory within the user's home directory (System.getProperty("user.home")), like
File f = new File(System.getProperty("user.home") + "/CtrlAltDelData");
f.mkdir();
File mySaveFile = new File (f, "save1.txt");

JAVA - Get access to a file in different subfolder

I am programming a file transfer, and i am having troubles with it.
In my current location i have created a folder called "Server Folder", where i will have files that the Client can transfer (I will be transfered with the same name, to the workspace directory), But every time i try to access it, it fails.
FILE_SERVER_PATH = "./ServerFolder/";
File fileToRead = new File(FILE_SERVER_PATH + fileName);
fileToRead = fileToRead.getParentFile();
if(fileToRead.exists()){
FileInputStream readingBuffer = new FileInputStream(fileToRead);
fileName is received throw datagram, and the name is correct. It always fails in the condition --> fileToRead.exists()
Can anyone please give me a tip?
Thx! :-)
try to use the folder path as absolute.
will help and work...current directory works only if you know in which directory you are in at the time of execution.

What is my directory when writing files in Android?

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
fos.write(string.getBytes());
fos.close();
When trying to delete one of those files, this is what I use, but it's returning false.
String tag = v.getTag().toString();
File file = new File(System.getProperty("user.dir")+"/"+tag);
String s = new Boolean (file.exists()).toString();
Toast.makeText(getApplicationContext(), s, 1500).show();
file.delete();
How can I overcome this problem?
Use getFileStreamPath(FILENAME) to find your file. From the docs:
Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.
Your current working directory.
To help diagnose the problem, use file.getAbsolutePath() to see the full path.
It could also be a permissions problem, if you're trying to delete from another application. If so, you may need to change to MODE_WORLD_WRITEABLE (insecure), or restructure your code so the create and delete are called by the same app.
EDIT: That was mostly incorrect. I didn't realize that openFileOutput didn't use the current working directory.
Use same contents as 'FILENAME' variable in your first snippet in the second snippet while trying to delete.
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Video";
File RootFile = new File(RootDir);
RootFile.mkdir();
FileOutputStream f = new FileOutputStream(new File(RootFile, "Sample.mp4"));
i used this code to save the video files to non-default location. Hope this will be useful to you.By default it is storing in sd card
For each application the Android system creates a "data/data/package of the application" directory.
Files are saved in the "files" folder under this directory
to change the default directory the above code will be used
the default working directory can be displayed using fileobject.getAbsolutePath()

Java: File output help

Fixed: Instead of calling isFile() I used exists() and it seems to be working fine. If possible could someone explain why this change worked?
I'm attempting to write out to an excel file but am having a problem when trying to create that file if the name already exists.
Basically I am taking a file that is uploaded to a server, reading it, and then outputting a report file in a new location with the same filename. I tried to do this by simply checking if the file already existed and then adding a number onto the filename. My code works if the file doesn't exist or if it exists without a number (e.g. filename.xls). If a file exists with the name "filename1.xls" the server just seems to hang when trying to write the file. What can do to fix this?
Here is my code:
String destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + ".xls";
int filenum = 1;
while (new File(destination).isFile()) {
destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + filenum + ".xls";
filenum++;
}
WritableWorkbook workbook = Workbook.createWorkbook(new File(destination));
That will happen if some process is still keeping the file open. E.g. you've created a FileInputStream on the file to read it, but are never calling close() on it after reading.
Unrelated to the problem, the expanded WAR folder is not the best place to use as a permanent storage. All those files in the expanded WAR folder will get lost whenever you redeploy the WAR. Also hardcoding a servletcontainer-specific path in the code makes it totally unportable.
If your actual intent is to return the Excel file on a per-request basis to the client using a servlet, then you should be using
WritableWorkbook workBook = Workbook.createWorkbook(response.getOutputStream());
// ...
This way it writes to the response immediately without the need for an intermediate file.
Use the File.createTempFile(prefix, suffix, directory) API:
String localName = new File(fileName).getName();
String nameNoExt = localName.substring(0, fileName.lastIndexOf("."));
String extension = localName.substring(fileName.lastIndexOf(".")); // need to include the .
File directory = new File("c:/apache-tomcat-7.0.8/webapps/reports/");
File destFile = File.createTempFile(nameNoExt, extension, directory)

Categories