Skip to content

Instantly share code, notes, and snippets.

@DHosseiny
Last active January 9, 2020 12:12
Show Gist options
  • Save DHosseiny/1d23a0fa1b9045429996c7db9afc5f6e to your computer and use it in GitHub Desktop.
Save DHosseiny/1d23a0fa1b9045429996c7db9afc5f6e to your computer and use it in GitHub Desktop.
Open any type of file
public class FileUtils {
/**
* @return The MIME type for the given file.
*/
public static String getMimeType(File file) {
String extension = getExtension(file.getName()).toLowerCase();
if (!TextUtils.isEmpty(extension) && extension.length() > 1)
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
return "application/octet-stream";
}
/**
* Gets the extension of a file name, like ".png" or ".jpg".
*
* @return Extension including the dot("."); "" if there is no extension or fileName is null.
*/
@NonNull
public static String getExtension(String fileName) {
if (fileName == null) {
return "";
}
int dot = fileName.lastIndexOf(".");
if (dot >= 0) {
return fileName.substring(dot);
} else {
// No extension.
return "";
}
}
}
override fun openFile(path: String) {
val newIntent = Intent(Intent.ACTION_VIEW)
val file = File(path)
val mimeType = FileUtils.getMimeType(file)
if (Build.VERSION.SDK_INT < 24) {
newIntent.setDataAndType(Uri.fromFile(file), mimeType)
} else newIntent.setDataAndType(Storage.getUriFromFile(file), mimeType)
newIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
if (Build.VERSION.SDK_INT >= 24) {
newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
if (newIntent.resolveActivity(requireContext().packageManager) != null) activity!!.startActivity(newIntent)
else Toast.makeText(activity, R.string.no_handler, Toast.LENGTH_LONG).show()
}
@mehdiyari
Copy link

mehdiyari commented Jan 6, 2020

Returns the extension of file (not including the dot), or an empty string if it doesn't have one
val fileExtension : ((path: String) -> String) = { File(it).extension }
Returns the extension of file (including the dot), or an empty string if it doesn't have one
val fileExtensionWithDot: ((path: String) -> (String)) = { File(it.extension).let { ext -> if (ext.isEmpty() "" else ".$ext") } }

@DHosseiny
Copy link
Author

There is no "extension" method in java.io.File package in android SDK 28.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment