0

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?

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.