how to convert URI to File Android 10 - android

how to get file object from URI OR convert URI to file object in android 10 and above versions.
final File file = new File(Environment.getExternalStorageDirectory(), "read.me");
Uri uri = Uri.fromFile(file);

You cannot convert the direct file to URI in android 10 instead of this you can make a copy of the file into your file directory which will help you to get a file object.
File f = getFile(getApplicationContext(), uri);
The below method provide you file object of URI and also you have a copy of the file in your file directory.
public static File getFile(Context context, Uri uri) throws IOException {
File destinationFilename = new File(context.getFilesDir().getPath() + File.separatorChar + queryName(context, uri));
try (InputStream ins = context.getContentResolver().openInputStream(uri)) {
createFileFromStream(ins, destinationFilename);
} catch (Exception ex) {
Log.e("Save File", ex.getMessage());
ex.printStackTrace();
}
return destinationFilename;
}
public static void createFileFromStream(InputStream ins, File destination) {
try (OutputStream os = new FileOutputStream(destination)) {
byte[] buffer = new byte[4096];
int length;
while ((length = ins.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.flush();
} catch (Exception ex) {
Log.e("Save File", ex.getMessage());
ex.printStackTrace();
}
}
private static String queryName(Context context, Uri uri) {
Cursor returnCursor =
context.getContentResolver().query(uri, null, null, null, null);
assert returnCursor != null;
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String name = returnCursor.getString(nameIndex);
returnCursor.close();
return name;
}
for more detail refer here

Related

How to save video using mediastore api in Android Q and above? (Video is in Internal/External Storage)

After the restrictions introduced in Android 10 and 11, I am finding it difficult to fetch a video in Internal / External Storage and copy into app specific directory, then use it(Permission Denied Error is thrown). For the image, I implemented the below:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
Bitmap bm = testObj.getScaledBitmap(bitmap);//used own method
Uri uriimg = testObj.storeImage(internalPath + imageName, bm);//used own method
I am unable to do the same for video.
Could you please provide the code for fetching video using Mediastore api and store in app specific directory or provide mediastore api video fetch example?
I also appreciate very much if i can get scopedstorage usage example using JAVA, because most examples i found are using Kotlin only.
Code:
After file picked on activity result, then check if its video, then
File file = new File(getPath(ProductFlipperActivity.this,uri));
getPath method:
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
Log.i("URI", uri + "");
String result = uri + "";
// DocumentProvider
// if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isKitKat && (result.contains("media.documents"))) {
String[] ary = result.split("/");
int length = ary.length;
String imgary = ary[length - 1];
final String[] dat = imgary.split("%3A");
final String docId = dat[1];
final String type = dat[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
dat[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
getDataColumn method():
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
if (checkPermissionREAD_EXTERNAL_STORAGE(context)) {
// do your stuff..
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
Get the file name and use storepdf method
String videoName = file.getName();
testObj.storePDF(internalPath + videoName, file);
storepdf method to save file in app specific directory:
//store pdf to sdcard
public Uri storePDF(String path, File file) {
Uri uri = null;
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(file);
String newFileName = path;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
return Uri.fromFile(file);
}
After using uri to save file and when i open inputstream to the real file path or uri, both throw error:
File file = new File(String.valueOf(uri));
//File file = new File(getPath(ProductFlipperActivity.this,uri));
String videoName = file.getName();
InputStream in = new FileInputStream(file);
OutputStream out = new FileOutputStream(new File(internalPath + videoName));
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Error Resolved by using the following code suggested by #blackapps:
File file = new File(getPath(ProductFlipperActivity.this,uri));
String videoName = file.getName();
InputStream in = this.getContentResolver().openInputStream(uri);
OutputStream out = this.getContentResolver().openOutputStream((Uri.fromFile(new File(internalPath + videoName))));
// Copy the bits from instream to outstream
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();

Firebase Storage download file to Pictures or Movie folder in Android Q

I was able to download a file from Firebase Storage to storage/emulated/0/Pictures which is a default folder for picture that is being used by most popular app as well such as Facebook or Instagram. Now that Android Q has a lot of behavioral changes in storing and accessing a file, my app no longer be able to download a file from the bucket when running in Android Q.
This is the code that write and download the file from the Firebase Storage bucket to a mass storage default folders like Pictures, Movies, Documents, etc. It works on Android M but on Q it will not work.
String state = Environment.getExternalStorageState();
String type = "";
if (downloadUri.contains("jpg") || downloadUri.contains("jpeg")
|| downloadUri.contains("png") || downloadUri.contains("webp")
|| downloadUri.contains("tiff") || downloadUri.contains("tif")) {
type = ".jpg";
folderName = "Images";
}
if (downloadUri.contains(".gif")){
type = ".gif";
folderName = "Images";
}
if (downloadUri.contains(".mp4") || downloadUri.contains(".avi")){
type = ".mp4";
folderName = "Videos";
}
//Create a path from root folder of primary storage
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Environment.DIRECTORY_PICTURES + "/MY_APP_NAME");
if (Environment.MEDIA_MOUNTED.equals(state)){
try {
if (dir.mkdirs())
Log.d(TAG, "New folder is created.");
}
catch (Exception e) {
e.printStackTrace();
Crashlytics.logException(e);
}
}
//Create a new file
File filePath = new File(dir, UUID.randomUUID().toString() + type);
//Creating a reference to the link
StorageReference httpsReference = FirebaseStorage.getInstance().getReferenceFromUrl(download_link_of_file_from_Firebase_Storage_bucket);
//Getting the file from the server
httpsReference.getFile(filePath).addOnProgressListener(taskSnapshot ->
showProgressNotification(taskSnapshot.getBytesTransferred(), taskSnapshot.getTotalByteCount(), requestCode)
);
With this it will download the files from server to your device storage with path storage/emulated/0/Pictures/MY_APP_NAME but with Android Q this will no longer work as many APIs became deprecated like Environment.getExternalStorageDirectory().
Using android:requestLegacyExternalStorage=true is a temporary solution but will no longer work soon on Android 11 and above.
So my question is how can I download files using Firebase Storage APIs on default Picture or Movie folder that is in the root instead of Android/data/com.myapp.package/files.
Does MediaStore and ContentResolver has solution for this? What changes do I need to apply?
Here is my solution:
Download file with Glide
public void downloadFile(Context context, String url){
String mimeType = getMimeType(url);
Glide.with(context).asFile().load(url).listener(new RequestListener<File>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
saveFile(context,resource, mimeType);
return false;
}
}).submit();
}
Get file mimeType
public static String getMimeType(String url) {
String mimeType = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return mimeType;
}
And save file to external storage
public Uri saveFile(Context context, File file, String mimeType) {
String folderName = "Pictures";
String extension = ".jpg";
if(mimeType.endsWith("gif")){
extension = ".gif";
}else if(mimeType.startsWith("image/")){
extension = ".jpg";
}else if(mimeType.startsWith("video/")){
extension = ".mp4";
folderName = "Movies";
}else if(mimeType.startsWith("audio/")){
extension = ".mp3";
folderName = "Music";
}else if(mimeType.endsWith("pdf")){
extension = ".pdf";
folderName = "Documents";
}
if (android.os.Build.VERSION.SDK_INT >= 29) {
ContentValues values = new ContentValues();
values.put(MediaStore.Files.FileColumns.MIME_TYPE, mimeType);
values.put(MediaStore.Files.FileColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
values.put(MediaStore.Files.FileColumns.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Files.FileColumns.RELATIVE_PATH, folderName);
values.put(MediaStore.Files.FileColumns.IS_PENDING, true);
values.put(MediaStore.Files.FileColumns.DISPLAY_NAME, "file_" + System.currentTimeMillis() + extension);
Uri uri = null;
if(mimeType.startsWith("image/")){
uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}else if(mimeType.startsWith("video/")){
uri = context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
}else if(mimeType.startsWith("audio/")){
uri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
}else if(mimeType.endsWith("pdf")){
uri = context.getContentResolver().insert(MediaStore.Files.getContentUri("external"), values);
}
if (uri != null) {
try {
saveFileToStream(context.getContentResolver().openInputStream(Uri.fromFile(file)), context.getContentResolver().openOutputStream(uri));
values.put(MediaStore.Video.Media.IS_PENDING, false);
context.getContentResolver().update(uri, values, null, null);
return uri;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
return null;
}
save file to stream
private void saveFileToStream(InputStream input, OutputStream outputStream) throws IOException {
try {
try (OutputStream output = outputStream ){
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
} finally {
input.close();
}
}
I tried with emulator Android 29. It works fine.
Note : getExternalStorageDirectory() was deprecated in API level 29. To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps. Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.
==NEW ANSWER==
If you wanted to monitor the download progress you can use getStream() of FirebaseStorage SDK like this:
httpsReference.getStream((state, inputStream) -> {
long totalBytes = state.getTotalByteCount();
long bytesDownloaded = 0;
byte[] buffer = new byte[1024];
int size;
while ((size = inputStream.read(buffer)) != -1) {
stream.write(buffer, 0, size);
bytesDownloaded += size;
showProgressNotification(bytesDownloaded, totalBytes, requestCode);
}
// Close the stream at the end of the Task
inputStream.close();
stream.flush();
stream.close();
}).addOnSuccessListener(taskSnapshot -> {
showDownloadFinishedNotification(downloadedFileUri, downloadURL, true, requestCode);
//Mark task as complete so the progress download notification whether success of fail will become removable
taskCompleted();
contentValues.put(MediaStore.Files.FileColumns.IS_PENDING, false);
resolver.update(uriResolve, contentValues, null, null);
}).addOnFailureListener(e -> {
Log.w(TAG, "download:FAILURE", e);
try {
stream.flush();
stream.close();
} catch (IOException ioException) {
ioException.printStackTrace();
FirebaseCrashlytics.getInstance().recordException(ioException);
}
FirebaseCrashlytics.getInstance().recordException(e);
//Send failure
showDownloadFinishedNotification(null, downloadURL, false, requestCode);
//Mark task as complete
taskCompleted();
});
==OLD ANSWER==
Finally after tons of hours I manage to do it but using .getBytes(maximum_file_size) instead of .getFile(file_object) as last resort.
Big big thanks to #Kasim for bringing up the idea of getBytes(maximum_file_size) with also sample code working with InputStream and OutputStream.By searching across S.O topic related to I/O also is a big help here and here
The idea here is .getByte(maximum_file_size) will download the file from the bucket and return a byte[] on its addOnSuccessListener callback. The downside is you must specify the file size you allowed to download and no download progress computation can be done AFAIK unless you do some work with outputStream.write(0,0,0); I tried to write it chunk by chunk like here but the solution is throwing ArrayIndexOutOfBoundsException since you must be accurate on working with index into an array.
So here is the code that let you saved file from your Firebase Storage Bucket to your device default directories: storage/emulated/0/Pictures, storage/emulated/0/Movies, storage/emulated/0/Documents, you name it
//Member variable but depending on your scope
private ByteArrayInputStream inputStream;
private Uri downloadedFileUri;
private OutputStream stream;
//Creating a reference to the link
StorageReference httpsReference = FirebaseStorage.getInstance().getReferenceFromUrl(downloadURL);
Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String type = "";
String mime = "";
String folderName = "";
if (downloadURL.contains("jpg") || downloadURL.contains("jpeg")
|| downloadURL.contains("png") || downloadURL.contains("webp")
|| downloadURL.contains("tiff") || downloadURL.contains("tif")) {
type = ".jpg";
mime = "image/*";
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
folderName = Environment.DIRECTORY_PICTURES;
}
if (downloadURL.contains(".gif")){
type = ".gif";
mime = "image/*";
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
folderName = Environment.DIRECTORY_PICTURES;
}
if (downloadURL.contains(".mp4") || downloadURL.contains(".avi")){
type = ".mp4";
mime = "video/*";
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
folderName = Environment.DIRECTORY_MOVIES;
}
if (downloadURL.contains(".mp3")){
type = ".mp3";
mime = "audio/*";
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
folderName = Environment.DIRECTORY_MUSIC;
}
final String relativeLocation = folderName + "/" + getString(R.string.app_name);
final ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, UUID.randomUUID().toString() + type);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mime); //Cannot be */*
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation);
ContentResolver resolver = getContentResolver();
Uri uriResolve = resolver.insert(contentUri, contentValues);
try {
if (uriResolve == null || uriResolve.getPath() == null) {
throw new IOException("Failed to create new MediaStore record.");
}
stream = resolver.openOutputStream(uriResolve);
//This is 1GB change this depending on you requirements
httpsReference.getBytes(1024 * 1024 * 1024)
.addOnSuccessListener(bytes -> {
try {
int bytesRead;
inputStream = new ByteArrayInputStream(bytes);
while ((bytesRead = inputStream.read(bytes)) > 0) {
stream.write(bytes, 0, bytesRead);
}
inputStream.close();
stream.flush();
stream.close();
//FINISH
} catch (IOException e) {
closeSession(resolver, uriResolve, e);
e.printStackTrace();
Crashlytics.logException(e);
}
});
} catch (IOException e) {
closeSession(resolver, uriResolve, e);
e.printStackTrace();
Crashlytics.logException(e);
}

SAF - File written in parent folder, not in the right path

My app wants to copy a file from a private app folder to a SAF folder that was created inside an user-selected SAF folder.
Folder creation is Ok.
The copy method is:
public static boolean copyFileToTargetSAFFolder(Context context, String filePath, String targetFolder, String destFileName )
{
Uri uri = Uri.parse(targetFolder);
String docId = DocumentsContract.getTreeDocumentId(uri);
Log.d("target folder uri",uri.toString());
Log.d("target folder id",docId);
Uri dirUri = DocumentsContract.buildDocumentUriUsingTree(uri, docId );
Log.d("dir uri",dirUri.toString());
Uri destUri = null;
try
{
destUri = DocumentsContract.createDocument(context.getContentResolver(), dirUri, "*/*", destFileName);
Log.d("dest uri",destUri.toString());
} catch (FileNotFoundException e )
{
e.printStackTrace();
return false;
}
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(filePath);
os = context.getContentResolver().openOutputStream( destUri, "w");
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
os.write(buffer, 0, length);
is.close();
os.flush();
os.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
the log is:
target folder uri: content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ffoldername/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ffoldername%2Fsubfoldername
target folder id: raw:/storage/emulated/0/Download/foldername
dir uri: content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ffoldername/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ffoldername
dest uri: content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ffoldername/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ffoldername%2Ffile.txt
It is indeed what happens on the filesystem. In fact the file is copied and created in the parent folder, not in the subfolder.
This code was from an answer on SO:
SAF - Invalid URI error from DocumentsContract.createDocument method (FileOutputStream copy)
I do not know if it is only a workaround but if I replace
String docId = DocumentsContract.getTreeDocumentId(uri);
with
String docId = DocumentsContract.getDocumentId(uri);
the method works.
public static boolean copyFileToTargetSAFFolder(Context context, String filePath, String targetFolder, String destFileName )
{
Uri uri = Uri.parse(targetFolder);
String docId = DocumentsContract.getDocumentId(uri);
Uri dirUri = DocumentsContract.buildDocumentUriUsingTree(uri, docId );
Uri destUri = null;
try
{
destUri = DocumentsContract.createDocument(context.getContentResolver(), dirUri, "*/*", destFileName);
} catch (FileNotFoundException e )
{
e.printStackTrace();
return false;
}
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(filePath);
os = context.getContentResolver().openOutputStream( destUri, "w");
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
os.write(buffer, 0, length);
is.close();
os.flush();
os.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
Indeed
now log has
dirUri content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ffoldername/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ffoldername%2Fsubfoldername
the file is correctly copied inside this folder.

How to copy files from 'assets' folder to sdcard?

I have a few files in the assets folder. I need to copy all of them to a folder say /sdcard/folder. I want to do this from within a thread. How do I do it?
If anyone else is having the same problem, this is how I did it
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Reference : Move file using Java
Based on your solution, I did something of my own to allow subfolders. Someone might find this helpful:
...
copyFileOrDir("myrootdir");
...
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
The solution above did not work due to some errors:
directory creation did not work
assets returned by Android contain also three folders: images, sounds and webkit
Added way to deal with large files: Add extension .mp3 to the file in the assets folder in your project and during copy the target file will be without the .mp3 extension
Here is the code (I left the Log statements but you can drop them now):
final static String TARGET_BASE_PATH = "/sdcard/appname/voices/";
private void copyFilesToSdCard() {
copyFileOrDir(""); // copy all files in assets folder in my project
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
copyFileOrDir( p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+filename);
in = assetManager.open(filename);
if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file
newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4);
else
newFileName = TARGET_BASE_PATH + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
}
EDIT: Corrected a misplaced ";" that was throwing a systematic "could not create dir" error.
I know this has been answered but I have a slightly more elegant way to copy from asset directory to a file on the sdcard. It requires no "for" loop but instead uses File Streams and Channels to do the work.
(Note) If using any type of compressed file, APK, PDF, ... you may want to rename the file extension before inserting into asset and then rename once you copy it to SDcard)
AssetManager am = context.getAssets();
AssetFileDescriptor afd = null;
try {
afd = am.openFd( "MyFile.dat");
// Create new file to copy into.
File file = new File(Environment.getExternalStorageDirectory() + java.io.File.separator + "NewFile.dat");
file.createNewFile();
copyFdToFile(afd.getFileDescriptor(), file);
} catch (IOException e) {
e.printStackTrace();
}
A way to copy a file without having to loop through it.
public static void copyFdToFile(FileDescriptor src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
This would be concise way in Kotlin.
fun AssetManager.copyRecursively(assetPath: String, targetFile: File) {
val list = list(assetPath)
if (list.isEmpty()) { // assetPath is file
open(assetPath).use { input ->
FileOutputStream(targetFile.absolutePath).use { output ->
input.copyTo(output)
output.flush()
}
}
} else { // assetPath is folder
targetFile.delete()
targetFile.mkdir()
list.forEach {
copyRecursively("$assetPath/$it", File(targetFile, it))
}
}
}
try out this it is much simpler ,this will help u:
// Open your local db as the input stream
InputStream myInput = _context.getAssets().open(YOUR FILE NAME);
// Path to the just created empty db
String outFileName =SDCARD PATH + YOUR FILE NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
Here is a cleaned up version for current Android devices, functional method design so that you can copy it to an AssetsHelper class e.g ;)
/**
*
* Info: prior to Android 2.3, any compressed asset file with an
* uncompressed size of over 1 MB cannot be read from the APK. So this
* should only be used if the device has android 2.3 or later running!
*
* #param c
* #param targetFolder
* e.g. {#link Environment#getExternalStorageDirectory()}
* #throws Exception
*/
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static boolean copyAssets(AssetManager assetManager,
File targetFolder) throws Exception {
Log.i(LOG_TAG, "Copying files from assets to folder " + targetFolder);
return copyAssets(assetManager, "", targetFolder);
}
/**
* The files will be copied at the location targetFolder+path so if you
* enter path="abc" and targetfolder="sdcard" the files will be located in
* "sdcard/abc"
*
* #param assetManager
* #param path
* #param targetFolder
* #return
* #throws Exception
*/
public static boolean copyAssets(AssetManager assetManager, String path,
File targetFolder) throws Exception {
Log.i(LOG_TAG, "Copying " + path + " to " + targetFolder);
String sources[] = assetManager.list(path);
if (sources.length == 0) { // its not a folder, so its a file:
copyAssetFileToFolder(assetManager, path, targetFolder);
} else { // its a folder:
if (path.startsWith("images") || path.startsWith("sounds")
|| path.startsWith("webkit")) {
Log.i(LOG_TAG, " > Skipping " + path);
return false;
}
File targetDir = new File(targetFolder, path);
targetDir.mkdirs();
for (String source : sources) {
String fullSourcePath = path.equals("") ? source : (path
+ File.separator + source);
copyAssets(assetManager, fullSourcePath, targetFolder);
}
}
return true;
}
private static void copyAssetFileToFolder(AssetManager assetManager,
String fullAssetPath, File targetBasePath) throws IOException {
InputStream in = assetManager.open(fullAssetPath);
OutputStream out = new FileOutputStream(new File(targetBasePath,
fullAssetPath));
byte[] buffer = new byte[16 * 1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
}
Modified this SO answer by #DannyA
private void copyAssets(String path, String outPath) {
AssetManager assetManager = this.getAssets();
String assets[];
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path, outPath);
} else {
String fullPath = outPath + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
if (!dir.mkdir()) Log.e(TAG, "No create external directory: " + dir );
for (String asset : assets) {
copyAssets(path + "/" + asset, outPath);
}
}
} catch (IOException ex) {
Log.e(TAG, "I/O Exception", ex);
}
}
private void copyFile(String filename, String outPath) {
AssetManager assetManager = this.getAssets();
InputStream in;
OutputStream out;
try {
in = assetManager.open(filename);
String newFileName = outPath + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
Preparations
in src/main/assets
add folder with name fold
Usage
File outDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
copyAssets("fold",outDir.toString());
In to the external directory find all files and directories that are within the fold assets
Using some of the concepts in the answers to this question, I wrote up a class called AssetCopier to make copying /assets/ simple. It's available on github and can be accessed with jitpack.io:
new AssetCopier(MainActivity.this)
.withFileScanning()
.copy("tocopy", destDir);
See https://github.com/flipagram/android-assetcopier for more details.
Copy all files and directories from assets to your folder!
for copying better use apache commons io
public void doCopyAssets() throws IOException {
File externalFilesDir = context.getExternalFilesDir(null);
doCopy("", externalFilesDir.getPath());
}
//THIS IS MAIN METHOD FOR COPY
private void doCopy(String dirName, String outPath) throws IOException {
String[] srcFiles = assets.list(dirName);//for directory
for (String srcFileName : srcFiles) {
String outFileName = outPath + File.separator + srcFileName;
String inFileName = dirName + File.separator + srcFileName;
if (dirName.equals("")) {// for first time
inFileName = srcFileName;
}
try {
InputStream inputStream = assets.open(inFileName);
copyAndClose(inputStream, new FileOutputStream(outFileName));
} catch (IOException e) {//if directory fails exception
new File(outFileName).mkdir();
doCopy(inFileName, outFileName);
}
}
}
public static void closeQuietly(AutoCloseable autoCloseable) {
try {
if(autoCloseable != null) {
autoCloseable.close();
}
} catch(IOException ioe) {
//skip
}
}
public static void copyAndClose(InputStream input, OutputStream output) throws IOException {
copy(input, output);
closeQuietly(input);
closeQuietly(output);
}
public static void copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int n = 0;
while(-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
}
Based on Rohith Nandakumar's solution, I did something of my own to copy files from a subfolder of assets (i.e. "assets/MyFolder"). Also, I'm checking if the file already exists in sdcard before trying to copy again.
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("MyFolder");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("MyFolder/"+filename);
File outFile = new File(getExternalFilesDir(null), filename);
if (!(outFile.exists())) {// File does not exist...
out = new FileOutputStream(outFile);
copyFile(in, out);
}
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Based on Yoram Cohen answer, here is a version that supports non static target directory.
Invoque with copyFileOrDir(getDataDir(), "") to write to internal app storage folder /data/data/pkg_name/
Supports subfolders.
Supports custom and non-static target directory
Avoids copying "images" etc fake asset folders like
private void copyFileOrDir(String TARGET_BASE_PATH, String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(TARGET_BASE_PATH, path);
} else {
String fullPath = TARGET_BASE_PATH + "/" + path;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
copyFileOrDir(TARGET_BASE_PATH, p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String TARGET_BASE_PATH, String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+filename);
in = assetManager.open(filename);
if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file
newFileName = TARGET_BASE_PATH + "/" + filename.substring(0, filename.length()-4);
else
newFileName = TARGET_BASE_PATH + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
}
You can do it in few steps using Kotlin, Here I am copying only few files instead of all from asstes to my apps files directory.
private fun copyRelatedAssets() {
val assets = arrayOf("myhome.html", "support.css", "myscript.js", "style.css")
assets.forEach {
val inputStream = requireContext().assets.open(it)
val nameSplit = it.split(".")
val name = nameSplit[0]
val extension = nameSplit[1]
val path = inputStream.getFilePath(requireContext().filesDir, name, extension)
Log.v(TAG, path)
}
}
And here is the extension function,
fun InputStream.getFilePath(dir: File, name: String, extension: String): String {
val file = File(dir, "$name.$extension")
val outputStream = FileOutputStream(file)
this.copyTo(outputStream, 4096)
return file.absolutePath
}
LOGCAT
/data/user/0/com.***.***/files/myhome.html
/data/user/0/com.***.***/files/support.css
/data/user/0/com.***.***/files/myscript.js
/data/user/0/com.***.***/files/style.css
There are essentially two ways to do this.
First, you can use AssetManager.open and, as described by Rohith Nandakumar and iterate over the inputstream.
Second, you can use AssetManager.openFd, which allows you to use a FileChannel (which has the transferTo and transferFrom methods), so you don't have to loop over the input stream yourself.
I will describe the openFd method here.
Compression
First you need to ensure that the file is stored uncompressed. The packaging system may choose to compress any file with an extension that is not marked as noCompress, and compressed files cannot be memory mapped, so you will have to rely on AssetManager.open in that case.
You can add a '.mp3' extension to your file to stop it from being compressed, but the proper solution is to modify your app/build.gradle file and add the following lines (to disable compression of PDF files)
aaptOptions {
noCompress 'pdf'
}
File packing
Note that the packager can still pack multiple files into one, so you can't just read the whole file the AssetManager gives you. You need to to ask the AssetFileDescriptor which parts you need.
Finding the correct part of the packed file
Once you've ensured your file is stored uncompressed, you can use the AssetManager.openFd method to obtain an AssetFileDescriptor, which can be used to obtain a FileInputStream (unlike AssetManager.open, which returns an InputStream) that contains a FileChannel. It also contains the starting offset (getStartOffset) and size (getLength), which you need to obtain the correct part of the file.
Implementation
An example implementation is given below:
private void copyFileFromAssets(String in_filename, File out_file){
Log.d("copyFileFromAssets", "Copying file '"+in_filename+"' to '"+out_file.toString()+"'");
AssetManager assetManager = getApplicationContext().getAssets();
FileChannel in_chan = null, out_chan = null;
try {
AssetFileDescriptor in_afd = assetManager.openFd(in_filename);
FileInputStream in_stream = in_afd.createInputStream();
in_chan = in_stream.getChannel();
Log.d("copyFileFromAssets", "Asset space in file: start = "+in_afd.getStartOffset()+", length = "+in_afd.getLength());
FileOutputStream out_stream = new FileOutputStream(out_file);
out_chan = out_stream.getChannel();
in_chan.transferTo(in_afd.getStartOffset(), in_afd.getLength(), out_chan);
} catch (IOException ioe){
Log.w("copyFileFromAssets", "Failed to copy file '"+in_filename+"' to external storage:"+ioe.toString());
} finally {
try {
if (in_chan != null) {
in_chan.close();
}
if (out_chan != null) {
out_chan.close();
}
} catch (IOException ioe){}
}
}
This answer is based on JPM's answer.
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
copyReadAssets();
}
private void copyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
String strDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ File.separator + "Pdfs";
File fileDir = new File(strDir);
fileDir.mkdirs(); // crear la ruta si no existe
File file = new File(fileDir, "example2.pdf");
try
{
in = assetManager.open("example.pdf"); //leer el archivo de assets
out = new BufferedOutputStream(new FileOutputStream(file)); //crear el archivo
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + "Pdfs" + "/example2.pdf"), "application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
change parts of code like these:
out = new BufferedOutputStream(new FileOutputStream(file));
the before example is for Pdfs, in case of to example .txt
FileOutputStream fos = new FileOutputStream(file);
Hi Guys I Did Something like this.
For N-th Depth Copy Folder and Files to copy.
Which Allows you to copy all the directory structure to copy from Android AssetManager :)
private void manageAssetFolderToSDcard()
{
try
{
String arg_assetDir = getApplicationContext().getPackageName();
String arg_destinationDir = FRConstants.ANDROID_DATA + arg_assetDir;
File FolderInCache = new File(arg_destinationDir);
if (!FolderInCache.exists())
{
copyDirorfileFromAssetManager(arg_assetDir, arg_destinationDir);
}
} catch (IOException e1)
{
e1.printStackTrace();
}
}
public String copyDirorfileFromAssetManager(String arg_assetDir, String arg_destinationDir) throws IOException
{
File sd_path = Environment.getExternalStorageDirectory();
String dest_dir_path = sd_path + addLeadingSlash(arg_destinationDir);
File dest_dir = new File(dest_dir_path);
createDir(dest_dir);
AssetManager asset_manager = getApplicationContext().getAssets();
String[] files = asset_manager.list(arg_assetDir);
for (int i = 0; i < files.length; i++)
{
String abs_asset_file_path = addTrailingSlash(arg_assetDir) + files[i];
String sub_files[] = asset_manager.list(abs_asset_file_path);
if (sub_files.length == 0)
{
// It is a file
String dest_file_path = addTrailingSlash(dest_dir_path) + files[i];
copyAssetFile(abs_asset_file_path, dest_file_path);
} else
{
// It is a sub directory
copyDirorfileFromAssetManager(abs_asset_file_path, addTrailingSlash(arg_destinationDir) + files[i]);
}
}
return dest_dir_path;
}
public void copyAssetFile(String assetFilePath, String destinationFilePath) throws IOException
{
InputStream in = getApplicationContext().getAssets().open(assetFilePath);
OutputStream out = new FileOutputStream(destinationFilePath);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
}
public String addTrailingSlash(String path)
{
if (path.charAt(path.length() - 1) != '/')
{
path += "/";
}
return path;
}
public String addLeadingSlash(String path)
{
if (path.charAt(0) != '/')
{
path = "/" + path;
}
return path;
}
public void createDir(File dir) throws IOException
{
if (dir.exists())
{
if (!dir.isDirectory())
{
throw new IOException("Can't create directory, a file is in the way");
}
} else
{
dir.mkdirs();
if (!dir.isDirectory())
{
throw new IOException("Unable to create directory");
}
}
}
In the end Create a Asynctask:
private class ManageAssetFolders extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... arg0)
{
manageAssetFolderToSDcard();
return null;
}
}
call it From your activity:
new ManageAssetFolders().execute();
Slight modification of above answer to copy a folder recursively and to accommodate custom destination.
public void copyFileOrDir(String path, String destinationDir) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path,destinationDir);
} else {
String fullPath = destinationDir + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i], destinationDir + path + "/" + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename, String destinationDir) {
AssetManager assetManager = this.getAssets();
String newFileName = destinationDir + "/" + filename;
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
new File(newFileName).setExecutable(true, false);
}
For those who are updating to Kotlin:
Following this steps to avoid FileUriExposedExceptions,
supposing user has granted WRITE_EXTERNAL_STORAGE permission and your file is in assets/pdfs/mypdf.pdf.
private fun openFile() {
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
try {
val file = File("${activity.getExternalFilesDir(null)}/$PDF_FILE_NAME")
if (!file.exists()) {
inputStream = activity.assets.open("$PDF_ASSETS_PATH/$PDF_FILE_NAME")
outputStream = FileOutputStream(file)
copyFile(inputStream, outputStream)
}
val uri = FileProvider.getUriForFile(
activity,
"${BuildConfig.APPLICATION_ID}.provider.GenericFileProvider",
file
)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "application/pdf")
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
}
activity.startActivity(intent)
} catch (ex: IOException) {
ex.printStackTrace()
} catch (ex: ActivityNotFoundException) {
ex.printStackTrace()
} finally {
inputStream?.close()
outputStream?.flush()
outputStream?.close()
}
}
#Throws(IOException::class)
private fun copyFile(input: InputStream, output: OutputStream) {
val buffer = ByteArray(1024)
var read: Int = input.read(buffer)
while (read != -1) {
output.write(buffer, 0, read)
read = input.read(buffer)
}
}
companion object {
private const val PDF_ASSETS_PATH = "pdfs"
private const val PDF_FILE_NAME = "mypdf.pdf"
}
That is my personalized text extractor class, hope that will be usefull.
package lorenzo.morelli.platedetector;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import com.googlecode.tesseract.android.TessBaseAPI;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TextExtractor {
private final Context context;
private final String dirName;
private final String language;
public TextExtractor(final Context context, final String dirName, final String language) {
this.context = context;
this.dirName = dirName;
this.language = language;
}
public String extractText(final Bitmap bitmap) {
final TessBaseAPI tessBaseApi = new TessBaseAPI();
final String datapath = this.context.getFilesDir()+ "/tesseract/";
checkFile(new File(datapath + this.dirName + "/"), datapath, this.dirName, this.language);
tessBaseApi.init(datapath, this.language);
tessBaseApi.setImage(bitmap);
final String extractedText = tessBaseApi.getUTF8Text();
tessBaseApi.end();
return extractedText;
}
private void checkFile(final File dir, final String datapath, final String dirName, final String language) {
//directory does not exist, but we can successfully create it
if (!dir.exists()&& dir.mkdirs()) {
copyFiles(datapath, dirName, language);
} //The directory exists, but there is no data file in it
if(dir.exists()) {
final String datafilepath = datapath + "/" + dirName + "/" + language + ".traineddata";
final File datafile = new File(datafilepath);
if (!datafile.exists()) {
copyFiles(datapath, dirName, language);
}
}
}
private void copyFiles(final String datapath, final String dirName, final String language) {
try {
//location we want the file to be at
final String filepath = datapath + "/" + dirName + "/" + language + ".traineddata";
//get access to AssetManager
final AssetManager assetManager = this.context.getAssets();
//open byte streams for reading/writing
final InputStream instream = assetManager.open(dirName + "/" + language + ".traineddata");
final OutputStream outstream = new FileOutputStream(filepath);
//copy the file to the location specified by filepath
byte[] buffer = new byte[1024];
int read;
while ((read = instream.read(buffer)) != -1) {
outstream.write(buffer, 0, read);
}
outstream.flush();
outstream.close();
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
To use that you need traineddata file. You can download trainddata file from this link.
Once you’ve downloaded the traineddata file you want, you need to make an Android Resource directory named assets in your android project. In the newly created assets folder, you need to create a regular directory named “tessdata” where you can place your traineddata files.
Finally you have to init the "TextExtractor" class in your MainActivity.
final TextExtractor textExtractor = new TextExtractor(this, "tessdata", "eng");
First parameter is the context, the second one is the name of directory just created and the last one is the language of traineddata just downloaded.
To extract text you have to call the "extractText" method:
final String text = textExtractor.extractText(imageWithText);
Note that extractText need a BitMap image to work!!
You can create a BitMap image from your drawable file with this line:
final BitMap image = BitmapFactory.decodeResource(getResources(), R.drawable.test_image);
If you need more support, I suggest you to follow this usefull guide: https://github.com/SamVanRoy/Android_OCR_App
In Kotlin it can be done with one line!
Add extension fun to InputStream
fun InputStream.toFile(to: File){
this.use { input->
to.outputStream().use { out->
input.copyTo(out)
}
}
}
then use it
MainActivity.kt
assets.open("test.zip").toFile(File(filesDir,"test.zip"))
This is by far the best solution I have been able to find on the internet.
I've used the following link https://gist.github.com/mhasby/026f02b33fcc4207b302a60645f6e217, but it had a single error which I fixed and then it works like a charm.
Here's my code. You can easily use it as it is an independent java class.
public class CopyAssets {
public static void copyAssets(Context context) {
AssetManager assetManager = context.getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
out = new FileOutputStream(Environment.getExternalStorageDirectory()+"/www/resources/" + filename);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
in = null;
} catch (IOException e) {
}
}
if (out != null) {
try {
out.flush();
out.close();
out = null;
} catch (IOException e) {
}
}
}
}
}
public static void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}}
As you can see, just create an instance of CopyAssets in your java class which has an activity. Now this part is important, as far as my testing and researching on the internet, You cannot use AssetManager if the class has no activity . It has something to do with the context of the java class.
Now, the c.copyAssets(getApplicationContext()) is an easy way to access the method, where c is and instance of CopyAssets class.
As per my requirement, I allowed the program to copy all my resource files inside the asset folder to the /www/resources/ of my internal directory.
You can easily find out the part where you need to make changes to the directory as per your use.
Feel free to ping me if you need any help.
You can also use Guava's ByteStream to copy the files from the assets folder to the SD card. This is the solution I ended up with which copies files recursively from the assets folder to the SD card:
/**
* Copies all assets in an assets directory to the SD file system.
*/
public class CopyAssetsToSDHelper {
public static void copyAssets(String assetDir, String targetDir, Context context)
throws IOException {
AssetManager assets = context.getAssets();
String[] list = assets.list(assetDir);
for (String f : Objects.requireNonNull(list)) {
if (f.indexOf(".") > 1) { // check, if this is a file
File outFile = new File(context.getExternalFilesDir(null),
String.format("%s/%s", targetDir, f));
File parentFile = outFile.getParentFile();
if (!Objects.requireNonNull(parentFile).exists()) {
if (!parentFile.mkdirs()) {
throw new IOException(String.format("Could not create directory %s.",
parentFile));
}
}
try (InputStream fin = assets.open(String.format("%s/%s", assetDir, f));
OutputStream fout = new FileOutputStream(outFile)) {
ByteStreams.copy(fin, fout);
}
} else { // This is a directory
copyAssets(String.format("%s/%s", assetDir, f), String.format("%s/%s", targetDir, f),
context);
}
}
}
}
Use AssetManager, it allows to read the files in the assets. Then use regular Java IO to write the files to sdcard.
Google is your friend, search for an example.

Convert file: Uri to File in Android

What is the easiest way to convert from an android.net.Uri object which holds a file: type to a java.io.File object in Android?
I tried the following but it doesn't work:
File file = new File(Environment.getExternalStorageDirectory(), "read.me");
Uri uri = Uri.fromFile(file);
File auxFile = new File(uri.toString());
assertEquals(file.getAbsolutePath(), auxFile.getAbsolutePath());
What you want is...
new File(uri.getPath());
... and not...
new File(uri.toString());
Notes
For an android.net.Uri object which is named uri and created exactly as in the question, uri.toString() returns a String in the format "file:///mnt/sdcard/myPicture.jpg", whereas uri.getPath() returns a String in the format "/mnt/sdcard/myPicture.jpg".
I understand that there are nuances to file storage in Android. My intention in this answer is to answer exactly what the questioner asked and not to get into the nuances.
use
InputStream inputStream = getContentResolver().openInputStream(uri);
directly and copy the file. Also see:
https://developer.android.com/guide/topics/providers/document-provider.html
After searching for a long time this is what worked for me:
File file = new File(getPath(uri));
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
Android + Kotlin
Add dependency for Kotlin Android extensions:
implementation 'androidx.core:core-ktx:{latestVersion}'
Get file from uri:
uri.toFile()
Best Solution
Create one simple FileUtil class & use to create, copy and rename the file
I used uri.toString() and uri.getPath() but not work for me.
I finally found this solution.
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileUtil {
private static final int EOF = -1;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private FileUtil() {
}
public static File from(Context context, Uri uri) throws IOException {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
String fileName = getFileName(context, uri);
String[] splitName = splitFileName(fileName);
File tempFile = File.createTempFile(splitName[0], splitName[1]);
tempFile = rename(tempFile, fileName);
tempFile.deleteOnExit();
FileOutputStream out = null;
try {
out = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (inputStream != null) {
copy(inputStream, out);
inputStream.close();
}
if (out != null) {
out.close();
}
return tempFile;
}
private static String[] splitFileName(String fileName) {
String name = fileName;
String extension = "";
int i = fileName.lastIndexOf(".");
if (i != -1) {
name = fileName.substring(0, i);
extension = fileName.substring(i);
}
return new String[]{name, extension};
}
private static String getFileName(Context context, Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf(File.separator);
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
private static File rename(File file, String newName) {
File newFile = new File(file.getParent(), newName);
if (!newFile.equals(file)) {
if (newFile.exists() && newFile.delete()) {
Log.d("FileUtil", "Delete old " + newName + " file");
}
if (file.renameTo(newFile)) {
Log.d("FileUtil", "Rename file to " + newName);
}
}
return newFile;
}
private static long copy(InputStream input, OutputStream output) throws IOException {
long count = 0;
int n;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
}
Use FileUtil class in your code
try {
File file = FileUtil.from(MainActivity.this,fileUri);
Log.d("file", "File...:::: uti - "+file .getPath()+" file -" + file + " : " + file .exists());
} catch (IOException e) {
e.printStackTrace();
}
EDIT: Sorry, I should have tested better before. This should work:
new File(new URI(androidURI.toString()));
URI is java.net.URI.
None of this works for me. I found this to be the working solution. But my case is specific to images.
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
With Kotlin it is even easier:
val file = File(uri.path)
Or if you are using Kotlin extensions for Android:
val file = uri.toFile()
UPDATE:
For images it return "Uri lacks 'file' scheme: content://"
Thanks for comment
One other way to reach that is create a Temporary File. to do that:
fun createTmpFileFromUri(context: Context, uri: Uri, fileName: String): File? {
return try {
val stream = context.contentResolver.openInputStream(uri)
val file = File.createTempFile(fileName, "", context.cacheDir)
org.apache.commons.io.FileUtils.copyInputStreamToFile(stream,file)
file
} catch (e: Exception) {
e.printStackTrace()
null
}
}
We use Apache Commons library FileUtils class. For adding it to your project:
implementation "commons-io:commons-io:2.7"
Note that MAKE SURE call to file.delete() after usage.
for more information checkout Documents.
If you have a Uri that conforms to the DocumentContract then you probably don't want to use File.
If you are on kotlin, use DocumentFile to do stuff you would in the old World use File for, and use ContentResolver to get streams.
Everything else is pretty much guaranteed to break.
#CommonsWare explained all things quite well. And we really should use the solution he proposed.
By the way, only information we could rely on when querying ContentResolver is a file's name and size as mentioned here:
Retrieving File Information | Android developers
As you could see there is an interface OpenableColumns that contains only two fields: DISPLAY_NAME and SIZE.
In my case I was need to retrieve EXIF information about a JPEG image and rotate it if needed before sending to a server. To do that I copied a file content into a temporary file using ContentResolver and openInputStream()
For this case, especially on Android, the way going for bytes is usually faster.
With this, I solved it by setting up a class FileHelper which is given the responsibility to deal with reading/writing bytes from/to file through stream and a class UriHelper which is given the responsibility to figure out path of Uri and permission.
As far as it's knew generally, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset) can help us to transfer string you want to bytes you need.
How to let UriHelper and FileHelper you to copy a picture noted by Uri into a file, you can run:
FileHelper.getInstance().copy(UriHelper.getInstance().toFile(uri_of_a_picture)
, FileHelper.getInstance().createExternalFile(null, UriHelper.getInstance().generateFileNameBasedOnTimeStamp()
+ UriHelper.getInstance().getFileName(uri_of_a_picture, context), context)
);
about my UriHelper:
public class UriHelper {
private static UriHelper INSTANCE = new UriHelper();
public static UriHelper getInstance() {
return INSTANCE;
}
#SuppressLint("SimpleDateFormat")
public String generateFileNameBasedOnTimeStamp() {
return new SimpleDateFormat("yyyyMMdd_hhmmss").format(new Date()) + ".jpeg";
}
/**
* if uri.getScheme.equals("content"), open it with a content resolver.
* if the uri.Scheme.equals("file"), open it using normal file methods.
*/
//
public File toFile(Uri uri) {
if (uri == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
return new File(uri.getPath());
}
public DocumentFile toDocumentFile(Uri uri) {
if (uri == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
return DocumentFile.fromFile(new File(uri.getPath()));
}
public Uri toUri(File file) {
if (file == null) return null;
Logger.d(">>> file path:" + file.getAbsolutePath());
return Uri.fromFile(file); //returns an immutable URI reference representing the file
}
public String getPath(Uri uri, Context context) {
if (uri == null) return null;
if (uri.getScheme() == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
String path;
if (uri.getScheme().equals("content")) {
//Cursor cursor = context.getContentResolver().query(uri, new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null);
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
Logger.e("!!! cursor is null");
return null;
}
if (cursor.getCount() >= 0) {
Logger.d("... the numbers of rows:" + cursor.getCount()
+ "and the numbers of columns:" + cursor.getColumnCount());
if (cursor.isBeforeFirst()) {
while (cursor.moveToNext()) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
}
} else {
cursor.moveToFirst();
do {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
} while (cursor.moveToNext());
}
path = uri.getPath();
cursor.close();
Logger.d("... content scheme:" + uri.getScheme() + " and return:" + path);
return path;
} else {
path = uri.getPath();
Logger.d("... content scheme:" + uri.getScheme()
+ " but the numbers of rows in the cursor is < 0:" + cursor.getCount()
+ " and return:" + path);
return path;
}
} else {
path = uri.getPath();
Logger.d("... not content scheme:" + uri.getScheme() + " and return:" + path);
return path;
}
}
public String getFileName(Uri uri, Context context) {
if (uri == null) return null;
if (uri.getScheme() == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
String path;
if (uri.getScheme().equals("content")) {
//Cursor cursor = context.getContentResolver().query(uri, new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null);
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
Logger.e("!!! cursor is null");
return null;
}
if (cursor.getCount() >= 0) {
Logger.d("... the numbers of rows:" + cursor.getCount()
+ "and the numbers of columns:" + cursor.getColumnCount());
if (cursor.isBeforeFirst()) {
while (cursor.moveToNext()) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
}
} else {
cursor.moveToFirst();
do {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
} while (cursor.moveToNext());
}
cursor.moveToFirst();
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
cursor.close();
Logger.d("... content scheme:" + uri.getScheme() + " and return:" + path);
return path;
} else {
path = uri.getLastPathSegment();
Logger.d("... content scheme:" + uri.getScheme()
+ " but the numbers of rows in the cursor is < 0:" + cursor.getCount()
+ " and return:" + path);
return path;
}
} else {
path = uri.getLastPathSegment();
Logger.d("... not content scheme:" + uri.getScheme() + " and return:" + path);
return path;
}
}
}
about my FileHelper:
public class FileHelper {
private static final String DEFAULT_DIR_NAME = "AmoFromTaiwan";
private static final int DEFAULT_BUFFER_SIZE = 1024;
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private static final int EOF = -1;
private static FileHelper INSTANCE = new FileHelper();
public static FileHelper getInstance() {
return INSTANCE;
}
private boolean isExternalStorageWritable(Context context) {
/*
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (context.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
Logger.e("!!! checkSelfPermission() not granted");
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}
private boolean isExternalStorageReadable(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (context.checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
Logger.e("!!! checkSelfPermission() not granted");
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}
#SuppressLint("SimpleDateFormat")
private String generateFileNameBasedOnTimeStamp() {
return new SimpleDateFormat("yyyyMMdd_hhmmss").format(new Date()) + ".jpeg";
}
public File createExternalFile(String dir_name, String file_name, Context context) {
String dir_path;
String file_path;
File dir ;
File file;
if (!isExternalStorageWritable(context)) {
Logger.e("!!! external storage not writable");
return null;
}
if (dir_name == null) {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + DEFAULT_DIR_NAME;
} else {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + dir_name;
}
Logger.d("... going to access an external dir:" + dir_path);
dir = new File(dir_path);
if (!dir.exists()) {
Logger.d("... going to mkdirs:" + dir_path);
if (!dir.mkdirs()) {
Logger.e("!!! failed to mkdirs");
return null;
}
}
if (file_name == null) {
file_path = dir_path + File.separator + generateFileNameBasedOnTimeStamp();
} else {
file_path = dir_path + File.separator + file_name;
}
Logger.d("... going to return an external dir:" + file_path);
file = new File(file_path);
if (file.exists()) {
Logger.d("... before creating to delete an external dir:" + file.getAbsolutePath());
if (!file.delete()) {
Logger.e("!!! failed to delete file");
return null;
}
}
return file;
}
public File createInternalFile(String dir_name, String file_name, Context context) {
String dir_path;
String file_path;
File dir ;
File file;
if (dir_name == null) {
dir = new ContextWrapper(context).getDir(DEFAULT_DIR_NAME, Context.MODE_PRIVATE);
} else {
dir = new ContextWrapper(context).getDir(dir_name, Context.MODE_PRIVATE);
}
dir_path = dir.getAbsolutePath();
Logger.d("... going to access an internal dir:" + dir_path);
if (!dir.exists()) {
Logger.d("... going to mkdirs:" + dir_path);
if (!dir.mkdirs()) {
Logger.e("!!! mkdirs failed");
return null;
}
}
if (file_name == null) {
file = new File(dir, generateFileNameBasedOnTimeStamp());
} else {
file = new File(dir, file_name);
}
file_path = file.getAbsolutePath();
Logger.d("... going to return an internal dir:" + file_path);
if (file.exists()) {
Logger.d("... before creating to delete an external dir:" + file.getAbsolutePath());
if (!file.delete()) {
Logger.e("!!! failed to delete file");
return null;
}
}
return file;
}
public File getExternalFile(String dir_name, String file_name, Context context) {
String dir_path;
String file_path;
File file;
if (!isExternalStorageWritable(context)) {
Logger.e("!!! external storage not writable");
return null;
}
if (dir_name == null) {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + DEFAULT_DIR_NAME;
} else {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + dir_name;
}
if (file_name == null) {
file_path = dir_path;
} else {
file_path = dir_path + File.separator + file_name;
}
Logger.d("... going to return an external file:" + file_path);
file = new File(file_path);
if (file.exists()) {
Logger.d("... file exists:" + file.getAbsolutePath());
} else {
Logger.e("!!! file does't exist:" + file.getAbsolutePath());
}
return file;
}
public File getInternalFile(String dir_name, String file_name, Context context) {
String file_path;
File dir ;
File file;
if (dir_name == null) {
dir = new ContextWrapper(context).getDir(DEFAULT_DIR_NAME, Context.MODE_PRIVATE);
} else {
dir = new ContextWrapper(context).getDir(dir_name, Context.MODE_PRIVATE);
}
if (file_name == null) {
file = new File(dir.getAbsolutePath());
} else {
file = new File(dir, file_name);
}
file_path = file.getAbsolutePath();
Logger.d("... going to return an internal dir:" + file_path);
if (file.exists()) {
Logger.d("... file exists:" + file.getAbsolutePath());
} else {
Logger.e("!!! file does't exist:" + file.getAbsolutePath());
}
return file;
}
private byte[] readBytesFromFile(File file) {
Logger.d(">>> path:" + file.getAbsolutePath());
FileInputStream fis;
long file_length;
byte[] buffer;
int offset = 0;
int next = 0;
if (!file.exists()) {
Logger.e("!!! file doesn't exists");
return null;
}
if (file.length() > Integer.MAX_VALUE) {
Logger.e("!!! file length is out of max of int");
return null;
} else {
file_length = file.length();
}
try {
fis = new FileInputStream(file);
//buffer = new byte[(int) file_length];
buffer = new byte[(int) file.length()];
long time_start = System.currentTimeMillis();
while (true) {
Logger.d("... now next:" + next + " and offset:" + offset);
if (System.currentTimeMillis() - time_start > 1000) {
Logger.e("!!! left due to time out");
break;
}
next = fis.read(buffer, offset, (buffer.length-offset));
if (next < 0 || offset >= buffer.length) {
Logger.d("... completed to read");
break;
}
offset += next;
}
//if (offset < buffer.length) {
if (offset < (int) file_length) {
Logger.e("!!! not complete to read");
return null;
}
fis.close();
return buffer;
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return null;
}
}
public byte[] readBytesFromFile(File file, boolean is_fis_fos_only) {
if (file == null) return null;
if (is_fis_fos_only) {
return readBytesFromFile(file);
}
Logger.d(">>> path:" + file.getAbsolutePath());
FileInputStream fis;
BufferedInputStream bis;
ByteArrayOutputStream bos;
byte[] buf = new byte[(int) file.length()];
int num_read;
if (!file.exists()) {
Logger.e("!!! file doesn't exists");
return null;
}
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
bos = new ByteArrayOutputStream();
long time_start = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - time_start > 1000) {
Logger.e("!!! left due to time out");
break;
}
num_read = bis.read(buf, 0, buf.length); //1024 bytes per call
if (num_read < 0) break;
bos.write(buf, 0, num_read);
}
buf = bos.toByteArray();
fis.close();
bis.close();
bos.close();
return buf;
} catch (FileNotFoundException e) {
e.printStackTrace();
Logger.e("!!! FileNotFoundException");
return null;
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return null;
}
}
/**
* streams (InputStream and OutputStream) transfer binary data
* if to write a string to a stream, must first convert it to bytes, or in other words encode it
*/
public boolean writeStringToFile(File file, String string, Charset charset) {
if (file == null) return false;
if (string == null) return false;
return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}
public boolean writeBytesToFile(File file, byte[] data) {
if (file == null) return false;
if (data == null) return false;
FileOutputStream fos;
BufferedOutputStream bos;
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data, 0, data.length);
bos.flush();
bos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return false;
}
return true;
}
/**
* io blocks until some input/output is available.
*/
public boolean copy(File source, File destination) {
if (source == null || destination == null) return false;
Logger.d(">>> source:" + source.getAbsolutePath() + ", destination:" + destination.getAbsolutePath());
try {
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination);
byte[] buffer = new byte[(int) source.length()];
int len;
while (EOF != (len = fis.read(buffer))) {
fos.write(buffer, 0, len);
}
if (true) { //debug
byte[] copies = readBytesFromFile(destination);
if (copies != null) {
int copy_len = copies.length;
Logger.d("... stream read and write done for " + copy_len + " bytes");
}
}
return destination.length() != 0;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void list(final String path, final String end, final List<File> files) {
Logger.d(">>> path:" + path + ", end:" + end);
File file = new File(path);
if (file.isDirectory()) {
for (File child : file.listFiles()){
list(child.getAbsolutePath(), end, files);
}
} else if (file.isFile()) {
if (end.equals("")) {
files.add(file);
} else {
if (file.getName().endsWith(end)) files.add(file);
}
}
}
public String[] splitFileName(File file, String split) {
String path;
String ext;
int lastIndexOfSplit = file.getAbsolutePath().lastIndexOf(split);
if (lastIndexOfSplit < 0) {
path = file.getAbsolutePath();
ext = "";
} else {
path = file.getAbsolutePath().substring(0, lastIndexOfSplit);
ext = file.getAbsolutePath().substring(lastIndexOfSplit);
}
return new String[] {path, ext};
}
public File rename(File old_file, String new_name) {
if (old_file == null || new_name == null) return null;
Logger.d(">>> old file path:" + old_file.getAbsolutePath() + ", new file name:" + new_name);
File new_file = new File(old_file, new_name);
if (!old_file.equals(new_file)) {
if (new_file.exists()) { //if find out previous file/dir at new path name exists
if (new_file.delete()) {
Logger.d("... succeeded to delete previous file at new abstract path name:" + new_file.getAbsolutePath());
} else {
Logger.e("!!! failed to delete previous file at new abstract path name");
return null;
}
}
if (old_file.renameTo(new_file)) {
Logger.d("... succeeded to rename old file to new abstract path name:" + new_file.getAbsolutePath());
} else {
Logger.e("!!! failed to rename old file to new abstract path name");
}
} else {
Logger.d("... new and old file have the equal abstract path name:" + new_file.getAbsolutePath());
}
return new_file;
}
public boolean remove(final String path, final String end) {
Logger.d(">>> path:" + path + ", end:" + end);
File file = new File(path);
boolean result = false;
if (file.isDirectory()) {
for (File child : file.listFiles()){
result = remove(child.getAbsolutePath(), end);
}
} else if (file.isFile()) {
if (end.equals("")) {
result = file.delete();
} else {
if (file.getName().endsWith(end)) result = file.delete();
}
} else {
Logger.e("!!! child is not file or directory");
}
return result;
}
#TargetApi(Build.VERSION_CODES.O)
public byte[] readNIOBytesFromFile(String path) throws IOException {
Logger.d(">>> path:" + path);
if (!Files.exists(Paths.get(path), LinkOption.NOFOLLOW_LINKS)) {
Logger.e("!!! file doesn't exists");
return null;
} else {
return Files.readAllBytes(Paths.get(path));
}
}
#TargetApi(Build.VERSION_CODES.O)
public File writeNIOBytesToFile(String dir, String name, byte[] data) {
Logger.d(">>> dir:" + dir + ", name:" + name);
Path path_dir;
Path path_file;
try {
if (!Files.exists(Paths.get(dir), LinkOption.NOFOLLOW_LINKS)) {
Logger.d("... make a dir");
path_dir = Files.createDirectories(Paths.get(dir));
if (path_dir == null) {
Logger.e("!!! failed to make a dir");
return null;
}
}
path_file = Files.write(Paths.get(name), data);
return path_file.toFile();
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return null;
}
}
#TargetApi(Build.VERSION_CODES.O)
public void listNIO(final String dir, final String end, final List<File> files) throws IOException {
Logger.d(">>> dir:" + dir + ", end:" + end);
Files.walkFileTree(Paths.get(dir), new FileVisitor<Path>() {
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
Logger.d("... file:" + dir.getFileName());
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
Logger.d("... file:" + file.getFileName());
if (end.equals("")) {
files.add(file.toFile());
} else {
if (file.endsWith(end)) files.add(file.toFile());
}
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
Logger.d("... file:" + file.getFileName());
if (end.equals("")) {
files.add(file.toFile());
} else {
if (file.endsWith(end)) files.add(file.toFile());
}
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
Logger.d("... file:" + dir.getFileName());
return FileVisitResult.CONTINUE;
}
});
}
/**
* recursion
*/
private int factorial (int x) {
if (x > 1) return (x*(factorial(x-1)));
else if (x == 1) return x;
else return 0;
}
}
For getting a file properly using a context uri,
Thanks to answers from #Mohsents , #Bogdan Kornev , #CommonsWare , #Juan Camilo Rodriguez Durán ;
I created an inputStream from uri and used this iStream to create a temporary file finally I am able to extract uri and path from this file.
fun createFileFromContentUri(fileUri : Uri) : File{
var fileName : String = ""
fileUri.let { returnUri ->
requireActivity().contentResolver.query(returnUri,null,null,null)
}?.use { cursor ->
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
cursor.moveToFirst()
fileName = cursor.getString(nameIndex)
}
// For extract file mimeType
val fileType: String? = fileUri.let { returnUri ->
requireActivity().contentResolver.getType(returnUri)
}
val iStream : InputStream = requireActivity().contentResolver.openInputStream(fileUri)!!
val outputDir : File = context?.cacheDir!!
val outputFile : File = File(outputDir,fileName)
copyStreamToFile(iStream, outputFile)
iStream.close()
return outputFile
}
fun copyStreamToFile(inputStream: InputStream, outputFile: File) {
inputStream.use { input ->
val outputStream = FileOutputStream(outputFile)
outputStream.use { output ->
val buffer = ByteArray(4 * 1024) // buffer size
while (true) {
val byteCount = input.read(buffer)
if (byteCount < 0) break
output.write(buffer, 0, byteCount)
}
output.flush()
}
}
}
I made this like the following way:
try {
readImageInformation(new File(contentUri.getPath()));
} catch (IOException e) {
readImageInformation(new File(getRealPathFromURI(context,
contentUri)));
}
public static String getRealPathFromURI(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj,
null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
So basically first I try to use a file i.e. picture taken by camera and saved on SD card. This don't work for image returned by:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
That case there is a need to convert Uri to real path by getRealPathFromURI() function.
So the conclusion is that it depends on what type of Uri you want to convert to File.
After lots of searches and trying different approaches, I found this one working on different Android versions:
First copy this function:
fun getRealPathFromUri(context: Context, contentUri: Uri): String {
var cursor: Cursor? = null
try {
val proj: Array<String> = arrayOf(MediaStore.Images.Media.DATA)
cursor = context.contentResolver.query(contentUri, proj, null, null, null)
val columnIndex = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor?.moveToFirst()
return columnIndex?.let { cursor?.getString(it) } ?: ""
} finally {
cursor?.close()
}
}
And then, generate a file like this:
File(getRealPathFromUri(context, uri))
uri.toString() gives me: "content://com.google.android.apps.nbu.files.provider/1/file%3A%2F%2F%2Fstorage%2Femulated%2F0%2FDownload%2Fbackup.file"
uri.getPath() gives me: "/1/file:///storage/emulated/0/Download/backup.file"
new File(uri.getPath()) gives me "/1/file:/storage/emulated/0/Download/backup.file".
So if you have an access to file and want to avoid using ContentResolver or directly reading file, the answer is:
private String uriToPath( Uri uri )
{
File backupFile = new File( uri.getPath() );
String absolutePath = backupFile.getAbsolutePath();
return absolutePath.substring( absolutePath.indexOf( ':' ) + 1 );
}
Error handling is skipped to simplify the answer
Use this to write to file, It worked for me when uri of gif was provided by GBoard and I have to copy that gif in my app data.
try {
String destinationFilePath = getExternalFilesDir("gifs") + "/tempFile.txt";
InputStream inputStream = getContentResolver().openInputStream(uri);
OutputStream outputStream = new FileOutputStream(destinationFilePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
Some libraries are required File Objects for a process like a retrofit, some image editors e.t.c.
to convert URI to file object or anything similar we have a way which is to support all android old versions and upcoming versions.
Step 1:
You have to create a new file inside FilesDir which is nonreadable to other Apps with the same name as our file and extension.
Step 2:
You have to copy the content of the URI to create a file by using InputStream.
File f = getFile(getApplicationContext(), uri);
public static File getFile(Context context, Uri uri) throws IOException {
File destinationFilename = new File(context.getFilesDir().getPath() + File.separatorChar + queryName(context, uri));
try (InputStream ins = context.getContentResolver().openInputStream(uri)) {
createFileFromStream(ins, destinationFilename);
} catch (Exception ex) {
Log.e("Save File", ex.getMessage());
ex.printStackTrace();
}
return destinationFilename;
}
public static void createFileFromStream(InputStream ins, File destination) {
try (OutputStream os = new FileOutputStream(destination)) {
byte[] buffer = new byte[4096];
int length;
while ((length = ins.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.flush();
} catch (Exception ex) {
Log.e("Save File", ex.getMessage());
ex.printStackTrace();
}
}
private static String queryName(Context context, Uri uri) {
Cursor returnCursor =
context.getContentResolver().query(uri, null, null, null, null);
assert returnCursor != null;
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String name = returnCursor.getString(nameIndex);
returnCursor.close();
return name;
}
Kotlin 2022
suspend fun Context.createFileFromAsset(assetName: String, fileName: String): File? {
return withContext(Dispatchers.IO) {
runCatching {
val stream = assets.open(assetName)
val file = File(cacheDir.absolutePath, fileName)
org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, file)
file
}.onFailure { Timber.e(it) }.getOrNull()
}
}
When done with the File make sure to call .delete() on it. Kudos to #Mohsent
For folks that are here looking for a solution for images in particular here it is.
private Bitmap getBitmapFromUri(Uri contentUri) {
String path = null;
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
path = cursor.getString(columnIndex);
}
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(path);
return bitmap;
}
File imageToUpload = new File(new URI(androidURI.toString())); works if this is a file u have created in the external storage.
For example file:///storage/emulated/0/(some directory and file name)
By the following code, I am able to get adobe application shared pdf file as a stream and saving into android application path
Android.Net.Uri fileuri =
(Android.Net.Uri)Intent.GetParcelableExtra(Intent.ExtraStream);
fileuri i am getting as {content://com.adobe.reader.fileprovider/root_external/
data/data/com.adobe.reader/files/Downloads/sample.pdf}
string filePath = fileuri.Path;
filePath I am gettings as root_external/data/data/com.adobe.reader/files/Download/sample.pdf
using (var stream = ContentResolver.OpenInputStream(fileuri))
{
byte[] fileByteArray = ToByteArray(stream); //only once you can read bytes from stream second time onwards it has zero bytes
string fileDestinationPath ="<path of your destination> "
convertByteArrayToPDF(fileByteArray, fileDestinationPath);//here pdf copied to your destination path
}
public static byte[] ToByteArray(Stream stream)
{
var bytes = new List<byte>();
int b;
while ((b = stream.ReadByte()) != -1)
bytes.Add((byte)b);
return bytes.ToArray();
}
public static string convertByteArrayToPDF(byte[] pdfByteArray, string filePath)
{
try
{
Java.IO.File data = new Java.IO.File(filePath);
Java.IO.OutputStream outPut = new Java.IO.FileOutputStream(data);
outPut.Write(pdfByteArray);
return data.AbsolutePath;
}
catch (System.Exception ex)
{
return string.Empty;
}
}
you can use this function for get file from uri in new android and older
fun getFileFromUri(context: Context, uri: Uri?): File? {
uri ?: return null
uri.path ?: return null
var newUriString = uri.toString()
newUriString = newUriString.replace(
"content://com.android.providers.downloads.documents/",
"content://com.android.providers.media.documents/"
)
newUriString = newUriString.replace(
"/msf%3A", "/image%3A"
)
val newUri = Uri.parse(newUriString)
var realPath = String()
val databaseUri: Uri
val selection: String?
val selectionArgs: Array<String>?
if (newUri.path?.contains("/document/image:") == true) {
databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
selection = "_id=?"
selectionArgs = arrayOf(DocumentsContract.getDocumentId(newUri).split(":")[1])
} else {
databaseUri = newUri
selection = null
selectionArgs = null
}
try {
val column = "_data"
val projection = arrayOf(column)
val cursor = context.contentResolver.query(
databaseUri,
projection,
selection,
selectionArgs,
null
)
cursor?.let {
if (it.moveToFirst()) {
val columnIndex = cursor.getColumnIndexOrThrow(column)
realPath = cursor.getString(columnIndex)
}
cursor.close()
}
} catch (e: Exception) {
Log.i("GetFileUri Exception:", e.message ?: "")
}
val path = realPath.ifEmpty {
when {
newUri.path?.contains("/document/raw:") == true -> newUri.path?.replace(
"/document/raw:",
""
)
newUri.path?.contains("/document/primary:") == true -> newUri.path?.replace(
"/document/primary:",
"/storage/emulated/0/"
)
else -> return null
}
}
return if (path.isNullOrEmpty()) null else File(path)
}
public String getRealPathFromURI(Uri uri)
{
String result;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
result = uri.getPath();
cursor.close();
return result;
}
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
return result;
}
Then using to get file from URI :
File finalFile = newFile(getRealPathFromURI(uri));
--HOPE CAN HELP YOU----
Get the input stream using content resolver
InputStream inputStream = getContentResolver().openInputStream(uri);
Then copy the input stream into a file
FileUtils.copyInputStreamToFile(inputStream, file);
Sample utility method:
private File toFile(Uri uri) throws IOException {
String displayName = "";
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if(cursor != null && cursor.moveToFirst()){
try {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}finally {
cursor.close();
}
}
File file = File.createTempFile(
FilenameUtils.getBaseName(displayName),
"."+FilenameUtils.getExtension(displayName)
);
InputStream inputStream = getContentResolver().openInputStream(uri);
FileUtils.copyInputStreamToFile(inputStream, file);
return file;
}
Extension base on #Jacek Kwiecień answer for convert image uri to file
fun Uri.toImageFile(context: Context): File? {
val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
val cursor = context.contentResolver.query(this, filePathColumn, null, null, null)
if (cursor != null) {
if (cursor.moveToFirst()) {
val columnIndex = cursor.getColumnIndex(filePathColumn[0])
val filePath = cursor.getString(columnIndex)
cursor.close()
return File(filePath)
}
cursor.close()
}
return null
}
If we use File(uri.getPath()), it will not work
If we use extension from android-ktx, it still not work too because
https://github.com/android/android-ktx/blob/master/src/main/java/androidx/core/net/Uri.kt
Add in onActivityResult, getting docx, or pdf file
var imageUriPath = ""
imageUriPath =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val split = (imageUri.path ? : "").split(":") //split the path.
split[1]
} else {
imageUri.path ? : ""
}
val file = File(imageUriPath)

Categories

Resources