Richard Jiang
Richard Jiang

Reputation: 1

Android get file using path (in String format)

My app needs to get an existing file for processing. Now I have the path of the file in String format, how can I get the File with it? Is it correct to do this:

File fileToSave = new File(dirOfTheFile);

Here dirOfTheFile is the path of the file. If I implement it in this way, will I get the existing file or the system will create another file for me?

Upvotes: 0

Views: 269

Answers (3)

Emil
Emil

Reputation: 2806

try this..

File fileToSave = new File(dirOfTheFile);
if(fileToSave.exists())
{
 // the file exists. use it
} else {
// create file here
}

if parent folder is not there you may have to call fileToSave.getParentFile().mkdirs() to create parent folders

Upvotes: 0

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95499

The File object is just a reference to a file (a wrapper around the path of the file); creating a new File object does not actually create or read the file; to do that, use FileInputStream to read, FileOutputStream to write, or the various File helper methods (like exists(), createNewFile(), etc.) for example to actually perform operations on the path in question. Note that, as others have pointed out, you should use one of the utilities provided by the system to locate directories on the internal or external storage, depending on where you want your files.

Upvotes: 2

David M
David M

Reputation: 841

That's what you want to do. If the file exists you'll get it. Otherwise you'll create it. You can check whether the file exists by calling fileToSave.exists() on it and act appropriately if it does not.

The new keyword is creating a File object in code, not necessarily a new file on the device.

I would caution you to not use hardcoded paths if you are for dirOfFile. For example, if you're accessing external storage, call Environment.getExternalStorageDirectory() instead of hardcoding /sdcard.

Upvotes: 2

Related Questions