Get a file given a path to the file - java

I want to get a file which i saved in a specific directory on my phone.
How can I find and get a ref to it so I can do with it something different like uploading to a server?
Thanks in advance.
Shiran

Well where do you store your file?
Store the file in a specific area such as
Environment.getExternalStorageDirectory()
Then when you want to read it, just use the file name used and the path obtained from the above method.

File f = new File("location");
Remember, if you're trying to access the sd card you need to set permissions. Then just handle the "file" in whatever way it is you're trying to do something.
If you're looking to use the SDCard check this post:
Permission to write to the SD card
[Edit - Example]
String filenameToWrite = "Test.jpg"
try{
File f = new File(Environment.getExternalStorageDirectory() + "/Photos/");
if (f.exists()){
File fileToWrite = new File(Environment.getExternalStorageDirectory() + "/Photos/" + filenameToWrite;
// Do something to write file, save bitmap, save byte stream, etc.
}
} catch(IOException e){
Log.e("File", "Could not save file, error occured: " + e.toString());
}
Here's a few getting started tutorials to help you understand how to read and write files in java. This (apart from the 'path') is a java question, not an Android one.
Tutorials:
http://beginwithjava.blogspot.com/2011/04/java-file-save-and-file-load-objects.html
http://www.roseindia.net/java/beginners/java-write-to-file.shtml

Related

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

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.

Android File Permissions issues on FilesDir()

I need to use a file in my application. If i upload the file to Data/Data/APP/files then it is added with -rw-rw-rw permissions which i can then use in my application. If i programatically write the file to getFilesDir() the exact same directory, i can see the 2 exact files in the same directory, however the programatically saved file has permissions -rw------- i cannot then access the file in my app using getfilesDir().
this is how the file is saved:
public void writeFileOnInternalStorage(Context mcoContext,String sFileName, String sBody){
File file = new File(getApplicationContext().getFilesDir(), "");
if(!file.exists()){
file.mkdir();
}
try{
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
}catch (Exception e){
e.printStackTrace();
}
}
How can i get the correct permissions to use the file. It may well not be a permissions issue it maybe the way i am saving the file? It is a .graphml extension file.
What do you mean by cannot access your file?
Take a look at this documentation (https://developer.android.com/training/data-storage), you don't need permission to access (read and write) files inside App-Specific Directory.
Edit:
I'm assuming that you already stored the file to the disk.
Please note that to read and write files inside App-Specific Directory doesn't require permission. You can read it using this simple code.
public File readFile(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
// do other stuff, like checking if the file exist, etc.
return file;
}
It doesn't matter what file extension it is, as long as the file exists, you will get it.
Actually there are so many articles that already cover this topic, please take a look to understand this topic better.

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");

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