Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Setting Where Photos are Saved

Kevin Faust
Kevin Faust
15,353 Points

Why do we create a temporary file instead of a a normal file?

Hi,

Ben creates a file like this:

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fileName = "IMG_" + timeStamp;
String fileType = ".jpg";


//create the file
File imageFile = null;
imageFile = File.createTempFile(fileName, fileType, mediaStorageDir);

How come Ben didn't create the file like this?:

imageFile = new File(mediaStorageDir, fileName + fileType);
imageFile.createNewFile();

I searched online and some have said they use createTempFile because it appends some random numbers to the end of the file name which makes the file name unique. Since Ben names the file using the current time, that makes an automatically unique file name. I am wondering whether there was a special reason Ben used the first code example above and which one is a better way to create files.