In Android, I want to create a pointer that points to already existing file by way of its filepath.
For example, my pseudo-code:
String path = "file/directory/filename";
File ptr = File's pointed to by the path
The Android documentation only provides methods with which one can create a new file through a file path, but I just want a File object that only points to an already existing File.
How do I do that?
Use:
String path = "file/directory/filename";
File ptr = new File(path);
// check If file exists.
if(ptr.exists()) {
// Your code Here if file exists
}
File f = new File(path);
f points to a virtual file , if the file doesnt exist, writing anything to it, will either create it or cause a system crash , depending on the type of content you are writing to it.
deleting a file that doesnt exist will also fail, so any operation with files must be encapsulated with try catch for IOException
see http://developer.android.com/reference/java/io/File.html
also on android's new Kitkat you explicity have to request the permission to READ_EXTRANL_STORAGE if you want to read, and WRITE_EXTERNAL_STORAGE if you want to write
Related
I'm trying to save file 0_0.xml in cache. So I do it like this
String fileName = "0_0.xml"
File file = new File(context.getCacheDir(), fileName);
if (file.exists()) {
...
} else {
file = File.createTempFile(fileName, null, context.getCacheDir());
FileOutputStream fos = new FileOutputStream(file);
try {
fos.write("some_string".getBytes());
} finally {
fos.close();
}
}
I've run my application for several times and wondered that it always could not find this file (if not file.exists() I write it like I described above) so it created new one each time. After that I listed all files in my cache and got something like this:
The question is why does my file change it's name and how can I access to it?
You call File.createTempFile to create the file. createTempFile() will compute a new, unique, name for your temporary file to avoid collisions with other operations that also need a temporary file.
If you want to keep the file and find it again, don't use createTempFile() to generate new and unique names. Instead use the same object (file) that you used when you checked to see if it existed.
I'm new to android development and I am working on a little project. What I am having some issue with is getting access to preloaded files.
In my app, I have an XML file that I preloaded (I just simply put it in my src folder in a package). How do I access them in my classes? I need to get a File object pointing to this file so that I can use it as I would I/O files. It seems like this should be trivial, but alas I am stuck.
Lets say the file is located under: com.app.preloadedFiles/file1.XML
I've tried something along the lines of this, but have had no success:
URL dir_url = ClassLoader.getSystemResource("preloadedFiles/file1.XML");
FIle file = new File(dir_url.toURI());
I solved this in my app by getting an InputStream to the file -- something like:
myContext.getAssets().open(fileName);
//read the data and store it in a variable
Then, if you truly need to do File related opterations with it, you can write it to a private (or public) directory and do your operations from you newly written file. Something like:
File storageDir = myContext.getDir(directoryName, Context.MODE_PRIVATE);
File myFile = new File(storageDir + File.separator + fileName);
//then, write the data to the file and manipulate it -- store the name for access via File later
This is my code to create a File Object. I am sure that the file is existing. However the file length() returns 0 and the exists() returns false too.
File uploadFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/DSC00050.jpg");
int totalSize = (int) uploadFile.length(); // Get size of file, bytes
After Writing File uploadFile = new File(...); it will not create the file itself.
AFAIK If File.exists() is returning false, then file just doesn't exist yet.
but yes You can create file by calling file.createNewFile()
if exists() returns false means the file does not exist or not accessible. Make sure that the SD card is mounted and that your app has sufficient permission i.e. READ_EXTERNAL_STORAGE. I suspect this is the problem because you should get exception in that case.
The other thing is to log the absolute file path uploadFile.getAbsolutePath() and make sure that it is correct.
Edit:
Are you sure that your image is directly under the DCIM folder not DCIM/Camera ? Use any file browser in Android and check the file complete path. I do not see any other problems in the code.
I have following question. I'd like to place a file named data.xml into sdcard/appname folder and use it for read and write application data.
So, when my main activity creates I need to check if this file exist:
public class appname extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.no_elements_l);
File file = getBaseContext().getFileStreamPath("/sdcard/appname/data.xml");
if(file.exists()) {
return;
} else {
// create a File object for the parent directory
File MTdirectory = new File("/sdcard/appname/");
// have the object build the directory structure, if needed.
MTdirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(MTdirectory, "data.xml");
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream DataFile = new FileOutputStream(outputFile);
}
But I have Unhandled exception type FileNotFoundException in last line. What's the problem? Uses permission WRITE_EXTERNAL_STORAGE is added to manifest.
Don't hardcode SDCard file path. It can be different for different devices and APIs.
For example it's /mnt/sdcard/ for Froyo while that of my Galaxy Nexus (JellyBean) is /storage/sdcard0/
Android Developer's Guide recommends using Environment.getExternalStorageDirectory()
Try doing it like this:
// Some Code
String path = Environment.getExternalStorageDirectory().getPath() + "/appname/";
File file = getBaseContext().getFileStreamPath(path);
// More Code
Does the path '/sdcard/appname' exist? You check for the file before you check for the sub-directory 'appname'. You need to check if that exists before you try to access a file inside it.
Also if you simply need the file to read-write application data why not just go with internal storage - one less manifest permission :) -> read here for internal storage
I want to save a file on internal storage into a specific folder. My code is:
File mediaDir = new File("media");
if (!mediaDir.exists()){
mediaDir.createNewFile();
mediaDir.mkdir();
}
File f = new File(getLocalPath());
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(data);
fos.close();
getLocalPath returns /data/data/myPackage/files/media/qmhUZU.jpg but when I want to create the media folder I'm getting the exception "java.io.IOException: Read-only file system". Any ideas how to write my files on internal phone storage in in folder media? Thanks.
You should use ContextWrapper like this:
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);
As always, refer to documentation, ContextWrapper has a lot to offer.
You should create the media dir appended to what getLocalPath() returns.
I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/ or /mnt/sdcard/. Let me explain.
If you execute the following statement:
File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();
It will resolve the path to the root /data/ somewhere higher up in Android.
I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/ without me translating anything on my own.
File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();
A quick fix would be to change your following code:
File f = new File(getLocalPath().replace("/data/data/", "/"));
Hope this helps
Write a file
When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:
getFilesDir()
Returns a File representing an internal directory for your app.
getCacheDir()
Returns a File representing an internal directory for your
app's temporary cache files.
Be sure to delete each file once it is no longer needed and implement a reasonable
size limit for the amount of memory you use at any given time, such as 1MB.
Caution: If the system runs low on storage, it may delete your cache files without warning.
Hi try this it will create directory + file inside it
File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
mediaDir.mkdir();
}
File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();
System.out.println("Your file has been written");