File.createTempFile() vs. new File()

1. Create file with random name

File file = File.createTempFile(String prefix, String suffix, File parent)
  • Actually create the file on disk and returns the file object
  • Create a file name in this format: prefix + random number + suffix
  • Useful when you need create temporary file on disk

2. Create file with exact name

File file = new File(File parent, String child);
file.createNewFile();
  • Actually create the file on disk and returns true if file get created successfully

  • File name will exactly as pass to child parameter

  • Useful when you need create permanent file on disk

3. Create only file object (in memory)

File file = new File(File parent, String child);
// doesn't create the file on disk until calling createNewFile() method
  • Only create the in memory and not actually on disk
  • Useful when you need just create file object (e.g just to pass it as parameter)

parent parameter can be one of these:

  1. App private directories

    • context.getCacheDir()
    • context.getExternalCacheDir()
    • and … (full list can be found here)
  2. Public directories

    • Environment.getExternalStorageDirectory()
    • Environment.getExternalStoragePublicDirectory(
      Environment.DIRECTORY_PICTURES)
    • and … (full list can be found here)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)