Related
I'm processing about 4 images / seconds from camera preview, save it to png File and send it to a server.
I couldn't yet identify why, but 1 time out of 2 the current session will store the .png as full black pictures. the File size is also very small (3kb vs the usual 700kb).
Here's how I store the Bitmap as a PNG file :
public static File SaveImagePNG(Bitmap subimg, String path, String filename) {
FileOutputStream out = null;
File sd = new File(path);
boolean success = true;
if (!sd.exists()) {
success = sd.mkdir();
}
if (success) {
File dest = new File(sd, filename);
try {
out = new FileOutputStream(dest);
if (subimg != null) {
// PNG is a lossless format, the compression factor (100) is ignored
subimg.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
}
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, e.getMessage());
} finally {
try {
if (out != null) {
out.close();
Log.d(TAG, "OK!!");
}
} catch (IOException e) {
Log.d(TAG, e.getMessage() + "Error");
e.printStackTrace();
}
}
return dest;
}
return null;
}
and here's how I call it :
val pathFilePNG = Environment.getExternalStorageDirectory().toString() + "/images"
requestParams[0]?.bitmapRGB?.setHasAlpha(false)
val imageFaceRGBFile = BitmapUtils.SaveImagePNG(requestParams[0]?.bitmapRGB, pathFilePNG, "faceRGB.png")
I share a image from social network and catch it with my app (following this link), but it catch a plain text instead of image, i try to parse to uri and url but it didn't work
void handleSendText(Intent intent) {
String sharedText2 = intent.getStringExtra(Intent.EXTRA_TEXT);
//Bn1.setText("Descargar Texto plano");
if (sharedText2 != null) { // check if is null or not
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Imgs/");
if(!folder.exists()){folder.mkdir();}// create folder
int diagonal = sharedText2.indexOf(":");
String sharedText = sharedText2.substring(diagonal + 1, sharedText2.length());
sharedText = sharedText.replace(" ", "");
if (!sharedText.startsWith("htt")) {// check if it's starts with http or not
sharedText = "https" + sharedText.substring(0, sharedText.indexOf("?"));
}
c = 1;
Bitmap bitmap = null;
Uri imageUri = Uri.parse(sharedText); // parse to uri
Time now = new Time(); // time
now.setToNow();
String nombre = "Imagen-" + now.weekDay + "-" + now.month + "-" + now.year + "-" + now.minute + "_" + now.second;// name of the image
if (imageUri != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
File file = null;
file = new File(folder.getAbsoluteFile(), nombre + ".jpg");
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
//bitmap.compress(Bitmap.CompressFormat.WEBP, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Tv1.setMovementMethod(new ScrollingMovementMethod());
Tv1.setText("Es una imagen\n" + imageUri + "\n" + file + "\nnombre:\n" + nombre); // show the name of the variables
if (bitmap == null) {
Tv1.setText(sharedText2 + "\n\nsharedtext\n" + sharedText);
} else {
Tv1.setText("SI quedo\n" + sharedText);
}
}
}
}
EXTRA_TEXT is supposed to be plain text. EXTRA_STREAM, on the other hand, is supposed to be a content: Uri (though often you will get a file: Uri instead). Presumably, the information you seek will be in EXTRA_STREAM, not EXTRA_TEXT.
I'm trying to use a directory that I have in my assets folder and access it as a File. Is it possible to access something in the Assets directory as a File? If not, how can I copy a directory from the Assets folder to the application's local directory?
I would copy a file like so:
try
{
InputStream stream = this.getAssets().open("myFile");
OutputStream output = new BufferedOutputStream(new FileOutputStream(this.getFilesDir() + "/myNewFile"));
byte data[] = new byte[1024];
int count;
while((count = stream.read(data)) != -1)
{
output.write(data, 0, count);
}
output.flush();
output.close();
stream.close();
}
catch(IOException e)
{
e.printStackTrace();
}
However, I'm not sure how I would be able to do this for a directory.
I would rather not build my infrastructure around something that doesn't work, so how would I copy a directory from Assets to a local directory, or is it possible to access a directory in my Assets as a File?
EDIT
This is how I solved it for my own project:
InputStream stream = null;
OutputStream output = null;
for(String fileName : this.getAssets().list("demopass"))
{
stream = this.getAssets().open("directoryName/" + fileName);
output = new BufferedOutputStream(new FileOutputStream(this.getFilesDir() + "/newDirectory/" + fileName));
byte data[] = new byte[1024];
int count;
while((count = stream.read(data)) != -1)
{
output.write(data, 0, count);
}
output.flush();
output.close();
stream.close();
stream = null;
output = null;
}
As suggested by dmaxi in comment above, you can use his link, with this code:
void displayFiles (AssetManager mgr, String path) {
try {
String list[] = mgr.list(path);
if (list != null)
for (int i=0; i<list.length; ++i)
{
Log.v("Assets:", path +"/"+ list[i]);
displayFiles(mgr, path + "/" + list[i]);
}
} catch (IOException e) {
Log.v("List error:", "can't list" + path);
}
}
I took it on this link.
Maybe you can combine this code with precedent one.
EDIT: see also AssetManager.
private void copyFolder(String name) {
// "Name" is the name of your folder!
AssetManager assetManager = getAssets();
String[] files = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
// Checking file on assets subfolder
try {
files = assetManager.list(name);
} catch (IOException e) {
Log.e("ERROR", "Failed to get asset file list.", e);
}
// Analyzing all file on assets subfolder
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
// First: checking if there is already a target folder
File folder = new File(Environment.getExternalStorageDirectory() + "/yourTargetFolder/" + name);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Moving all the files on external SD
try {
in = assetManager.open(name + "/" +filename);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/yourTargetFolder/" + name + "/" + filename);
Log.i("WEBVIEW", Environment.getExternalStorageDirectory() + "/yourTargetFolder/" + name + "/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("ERROR", "Failed to copy asset file: " + filename, e);
} finally {
// Edit 3 (after MMs comment)
in.close();
in = null;
out.flush();
out.close();
out = null;
}
}
else {
// Do something else on failure
}
}
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
} else {
// Something else is wrong. It may be one of many other states, but all we need
// is to know is we can neither read nor write
}
}
// Method used by copyAssets() on purpose to copy a file.
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);
}
}
EDIT 2: i'have added an example above: this piece of code copy only a specific folder from assets, to sd card. Let me know if it works!
Here is a recursive function to do this - copyAssetFolder.
public static boolean copyAssetFolder(Context context, String srcName, String dstName) {
try {
boolean result = true;
String fileList[] = context.getAssets().list(srcName);
if (fileList == null) return false;
if (fileList.length == 0) {
result = copyAssetFile(context, srcName, dstName);
} else {
File file = new File(dstName);
result = file.mkdirs();
for (String filename : fileList) {
result &= copyAssetFolder(context, srcName + File.separator + filename, dstName + File.separator + filename);
}
}
return result;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean copyAssetFile(Context context, String srcName, String dstName) {
try {
InputStream in = context.getAssets().open(srcName);
File outFile = new File(dstName);
OutputStream out = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
Or the same in Kotlin
fun AssetManager.copyAssetFolder(srcName: String, dstName: String): Boolean {
return try {
var result = true
val fileList = this.list(srcName) ?: return false
if (fileList.isEmpty()) {
result = copyAssetFile(srcName, dstName)
} else {
val file = File(dstName)
result = file.mkdirs()
for (filename in fileList) {
result = result and copyAssetFolder(
srcName + separator.toString() + filename,
dstName + separator.toString() + filename
)
}
}
result
} catch (e: IOException) {
e.printStackTrace()
false
}
}
fun AssetManager.copyAssetFile(srcName: String, dstName: String): Boolean {
return try {
val inStream = this.open(srcName)
val outFile = File(dstName)
val out: OutputStream = FileOutputStream(outFile)
val buffer = ByteArray(1024)
var read: Int
while (inStream.read(buffer).also { read = it } != -1) {
out.write(buffer, 0, read)
}
inStream.close()
out.close()
true
} catch (e: IOException) {
e.printStackTrace()
false
}
}
You can use following method for copying your asset folder to a location in your SD Card. From your calling method just call moveAssetToStorageDir("") for moving entire asset folder. In case of sub folders you can specify the relative path inside the asset folder.
public void moveAssetToStorageDir(String path){
File file = getExternalFilesDir(null);
String rootPath = file.getPath() + "/" + path;
try{
String [] paths = getAssets().list(path);
for(int i=0; i<paths.length; i++){
if(paths[i].indexOf(".")==-1){
File dir = new File(rootPath + paths[i]);
dir.mkdir();
moveAssetToStorageDir(paths[i]);
}else {
File dest = null;
InputStream in = null;
if(path.length() == 0) {
dest = new File(rootPath + paths[i]);
in = getAssets().open(paths[i]);
}else{
dest = new File(rootPath + "/" + paths[i]);
in = getAssets().open(path + "/" + paths[i]);
}
dest.createNewFile();
FileOutputStream out = new FileOutputStream(dest);
byte [] buff = new byte[in.available()];
in.read(buff);
out.write(buff);
out.close();
in.close();
}
}
}catch (Exception exp){
exp.printStackTrace();
}
}
Here is the clean version of the OP's answer.
public void copyAssetFolderToFolder(Context activity, String assetsFolder, File destinationFolder) {
InputStream stream = null;
OutputStream output = null;
try {
for (String fileName : activity.getAssets().list(assetsFolder)) {
stream = activity.getAssets().open(assetsFolder + ((assetsFolder.endsWith(File.pathSeparator))?"":File.pathSeparator) + fileName);
output = new BufferedOutputStream(new FileOutputStream(new File(destinationFolder, fileName)));
byte data[] = new byte[1024];
int count;
while ((count = stream.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
stream.close();
stream = null;
output = null;
}
} catch (/*any*/Exception e){e.printStackTrace();}
}
For future reference, please save everyone the trouble and post contextually complete source listings. This site can be a great coding resource for beginners and experts, if only you would post complete answers. One cannot assume that anyone else "understands" where a random block of code belongs, or the context that the code is supposed to be executed within.
This sample calls for the context of an activity, which houses the getAssets() method. Within the android platform, their are other classes besides Activity which can supply this context. One example is the (generic reference) Service class.
Moving an arbitrary folder of directories and files from Assets
The thing is... Assets are special. You cannot wrap it in a File object and ask isDirectory() and you cannot pass these assets into the NDK. So it is better to wrap them up and move them to a cache directory or onto the SDCard which is why you're here.
I've seen many SO answers that involve some version of rolling through an array of fileOrDirectoryName strings and then creating directories followed by a recursive call and copying individual files. Which leads you to create a folder or file and you cannot tell from an asset which you have.
Make it a Zip file
My recommendation is to take each arbitrary collection of assets that you want to ship to the SDCard or an internal cache folder and Zip it up. The problem is structured in an way more compatible with the Assets concept.
AssetManager assetManager = context.getAssets();
String fullAssetPath = fromAssetPath + "/" + zipFilename;
String toPath = "/wherever/I/want";
try {
InputStream inputStream = assetManager.open(fullAssetPath);
ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
ZipEntry zipEntry;
byte[] buffer = new byte[8192];
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String fileOrDirectory = zipEntry.getName();
Uri.Builder builder = new Uri.Builder();
builder.scheme("file");
builder.appendPath(toPath);
builder.appendPath(fileOrDirectory);
String fullToPath = builder.build().getPath();
if (zipEntry.isDirectory()) {
File directory = new File(fullToPath);
directory.mkdirs();
continue;
}
FileOutputStream fileOutputStream = new FileOutputStream(fullToPath);
while ((count = zipInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.close();
zipInputStream.closeEntry();
}
zipInputStream.close();
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage());
}
Small note about buffer sizes
I've seen a lot of examples involving very small buffer sizes, for example 1024. Unless you just want to waste time feel free to try larger byte buffer sizes. Even my choice of 8192 is probably small on modern hardware.
Avoiding Stringy paths
Notice the use of Uri.Builder to construct the path. I much prefer this style of path construction over directory + "/" + file. Then you're in the business, for the sake of consistency avoiding assigning String d = "myDirectory/" or String f = "/file.txt" and other such string hacking nonsense.
Here's a recursive solution written in kotlin. It works with both files and dirs.
Usage - copyAssetDir(context, "<asset path>", "<dest dir>")
import android.content.Context
import java.io.File
import java.io.FileOutputStream
fun copyAssetDir(context: Context, assetPath: String, destDirPath: String) {
walkAssetDir(context, assetPath) {
copyAssetFile(context, it, "$destDirPath/$it")
}
}
fun walkAssetDir(context: Context, assetPath: String, callback: ((String) -> Unit)) {
val children = context.assets.list(assetPath) ?: return
if (children.isEmpty()) {
callback(assetPath)
} else {
for (child in children) {
walkAssetDir(context, "$assetPath/$child", callback)
}
}
}
fun copyAssetFile(context: Context, assetPath: String, destPath: String): File {
val destFile = File(destPath)
File(destFile.parent).mkdirs()
destFile.createNewFile()
context.assets.open(assetPath).use { src ->
FileOutputStream(destFile).use { dest ->
src.copyTo(dest)
}
}
return destFile
}
This is code for copy assets folder with directory and files both copy into sdcard folder...
this one works perfectly for me...
public 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());
}
}
I'm trying to use a directory that I have in my assets folder and access it as a File. Is it possible to access something in the Assets directory as a File? If not, how can I copy a directory from the Assets folder to the application's local directory?
I would copy a file like so:
try
{
InputStream stream = this.getAssets().open("myFile");
OutputStream output = new BufferedOutputStream(new FileOutputStream(this.getFilesDir() + "/myNewFile"));
byte data[] = new byte[1024];
int count;
while((count = stream.read(data)) != -1)
{
output.write(data, 0, count);
}
output.flush();
output.close();
stream.close();
}
catch(IOException e)
{
e.printStackTrace();
}
However, I'm not sure how I would be able to do this for a directory.
I would rather not build my infrastructure around something that doesn't work, so how would I copy a directory from Assets to a local directory, or is it possible to access a directory in my Assets as a File?
EDIT
This is how I solved it for my own project:
InputStream stream = null;
OutputStream output = null;
for(String fileName : this.getAssets().list("demopass"))
{
stream = this.getAssets().open("directoryName/" + fileName);
output = new BufferedOutputStream(new FileOutputStream(this.getFilesDir() + "/newDirectory/" + fileName));
byte data[] = new byte[1024];
int count;
while((count = stream.read(data)) != -1)
{
output.write(data, 0, count);
}
output.flush();
output.close();
stream.close();
stream = null;
output = null;
}
As suggested by dmaxi in comment above, you can use his link, with this code:
void displayFiles (AssetManager mgr, String path) {
try {
String list[] = mgr.list(path);
if (list != null)
for (int i=0; i<list.length; ++i)
{
Log.v("Assets:", path +"/"+ list[i]);
displayFiles(mgr, path + "/" + list[i]);
}
} catch (IOException e) {
Log.v("List error:", "can't list" + path);
}
}
I took it on this link.
Maybe you can combine this code with precedent one.
EDIT: see also AssetManager.
private void copyFolder(String name) {
// "Name" is the name of your folder!
AssetManager assetManager = getAssets();
String[] files = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
// Checking file on assets subfolder
try {
files = assetManager.list(name);
} catch (IOException e) {
Log.e("ERROR", "Failed to get asset file list.", e);
}
// Analyzing all file on assets subfolder
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
// First: checking if there is already a target folder
File folder = new File(Environment.getExternalStorageDirectory() + "/yourTargetFolder/" + name);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Moving all the files on external SD
try {
in = assetManager.open(name + "/" +filename);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/yourTargetFolder/" + name + "/" + filename);
Log.i("WEBVIEW", Environment.getExternalStorageDirectory() + "/yourTargetFolder/" + name + "/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("ERROR", "Failed to copy asset file: " + filename, e);
} finally {
// Edit 3 (after MMs comment)
in.close();
in = null;
out.flush();
out.close();
out = null;
}
}
else {
// Do something else on failure
}
}
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
} else {
// Something else is wrong. It may be one of many other states, but all we need
// is to know is we can neither read nor write
}
}
// Method used by copyAssets() on purpose to copy a file.
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);
}
}
EDIT 2: i'have added an example above: this piece of code copy only a specific folder from assets, to sd card. Let me know if it works!
Here is a recursive function to do this - copyAssetFolder.
public static boolean copyAssetFolder(Context context, String srcName, String dstName) {
try {
boolean result = true;
String fileList[] = context.getAssets().list(srcName);
if (fileList == null) return false;
if (fileList.length == 0) {
result = copyAssetFile(context, srcName, dstName);
} else {
File file = new File(dstName);
result = file.mkdirs();
for (String filename : fileList) {
result &= copyAssetFolder(context, srcName + File.separator + filename, dstName + File.separator + filename);
}
}
return result;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean copyAssetFile(Context context, String srcName, String dstName) {
try {
InputStream in = context.getAssets().open(srcName);
File outFile = new File(dstName);
OutputStream out = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
Or the same in Kotlin
fun AssetManager.copyAssetFolder(srcName: String, dstName: String): Boolean {
return try {
var result = true
val fileList = this.list(srcName) ?: return false
if (fileList.isEmpty()) {
result = copyAssetFile(srcName, dstName)
} else {
val file = File(dstName)
result = file.mkdirs()
for (filename in fileList) {
result = result and copyAssetFolder(
srcName + separator.toString() + filename,
dstName + separator.toString() + filename
)
}
}
result
} catch (e: IOException) {
e.printStackTrace()
false
}
}
fun AssetManager.copyAssetFile(srcName: String, dstName: String): Boolean {
return try {
val inStream = this.open(srcName)
val outFile = File(dstName)
val out: OutputStream = FileOutputStream(outFile)
val buffer = ByteArray(1024)
var read: Int
while (inStream.read(buffer).also { read = it } != -1) {
out.write(buffer, 0, read)
}
inStream.close()
out.close()
true
} catch (e: IOException) {
e.printStackTrace()
false
}
}
You can use following method for copying your asset folder to a location in your SD Card. From your calling method just call moveAssetToStorageDir("") for moving entire asset folder. In case of sub folders you can specify the relative path inside the asset folder.
public void moveAssetToStorageDir(String path){
File file = getExternalFilesDir(null);
String rootPath = file.getPath() + "/" + path;
try{
String [] paths = getAssets().list(path);
for(int i=0; i<paths.length; i++){
if(paths[i].indexOf(".")==-1){
File dir = new File(rootPath + paths[i]);
dir.mkdir();
moveAssetToStorageDir(paths[i]);
}else {
File dest = null;
InputStream in = null;
if(path.length() == 0) {
dest = new File(rootPath + paths[i]);
in = getAssets().open(paths[i]);
}else{
dest = new File(rootPath + "/" + paths[i]);
in = getAssets().open(path + "/" + paths[i]);
}
dest.createNewFile();
FileOutputStream out = new FileOutputStream(dest);
byte [] buff = new byte[in.available()];
in.read(buff);
out.write(buff);
out.close();
in.close();
}
}
}catch (Exception exp){
exp.printStackTrace();
}
}
Here is the clean version of the OP's answer.
public void copyAssetFolderToFolder(Context activity, String assetsFolder, File destinationFolder) {
InputStream stream = null;
OutputStream output = null;
try {
for (String fileName : activity.getAssets().list(assetsFolder)) {
stream = activity.getAssets().open(assetsFolder + ((assetsFolder.endsWith(File.pathSeparator))?"":File.pathSeparator) + fileName);
output = new BufferedOutputStream(new FileOutputStream(new File(destinationFolder, fileName)));
byte data[] = new byte[1024];
int count;
while ((count = stream.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
stream.close();
stream = null;
output = null;
}
} catch (/*any*/Exception e){e.printStackTrace();}
}
For future reference, please save everyone the trouble and post contextually complete source listings. This site can be a great coding resource for beginners and experts, if only you would post complete answers. One cannot assume that anyone else "understands" where a random block of code belongs, or the context that the code is supposed to be executed within.
This sample calls for the context of an activity, which houses the getAssets() method. Within the android platform, their are other classes besides Activity which can supply this context. One example is the (generic reference) Service class.
Moving an arbitrary folder of directories and files from Assets
The thing is... Assets are special. You cannot wrap it in a File object and ask isDirectory() and you cannot pass these assets into the NDK. So it is better to wrap them up and move them to a cache directory or onto the SDCard which is why you're here.
I've seen many SO answers that involve some version of rolling through an array of fileOrDirectoryName strings and then creating directories followed by a recursive call and copying individual files. Which leads you to create a folder or file and you cannot tell from an asset which you have.
Make it a Zip file
My recommendation is to take each arbitrary collection of assets that you want to ship to the SDCard or an internal cache folder and Zip it up. The problem is structured in an way more compatible with the Assets concept.
AssetManager assetManager = context.getAssets();
String fullAssetPath = fromAssetPath + "/" + zipFilename;
String toPath = "/wherever/I/want";
try {
InputStream inputStream = assetManager.open(fullAssetPath);
ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
ZipEntry zipEntry;
byte[] buffer = new byte[8192];
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String fileOrDirectory = zipEntry.getName();
Uri.Builder builder = new Uri.Builder();
builder.scheme("file");
builder.appendPath(toPath);
builder.appendPath(fileOrDirectory);
String fullToPath = builder.build().getPath();
if (zipEntry.isDirectory()) {
File directory = new File(fullToPath);
directory.mkdirs();
continue;
}
FileOutputStream fileOutputStream = new FileOutputStream(fullToPath);
while ((count = zipInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.close();
zipInputStream.closeEntry();
}
zipInputStream.close();
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage());
}
Small note about buffer sizes
I've seen a lot of examples involving very small buffer sizes, for example 1024. Unless you just want to waste time feel free to try larger byte buffer sizes. Even my choice of 8192 is probably small on modern hardware.
Avoiding Stringy paths
Notice the use of Uri.Builder to construct the path. I much prefer this style of path construction over directory + "/" + file. Then you're in the business, for the sake of consistency avoiding assigning String d = "myDirectory/" or String f = "/file.txt" and other such string hacking nonsense.
Here's a recursive solution written in kotlin. It works with both files and dirs.
Usage - copyAssetDir(context, "<asset path>", "<dest dir>")
import android.content.Context
import java.io.File
import java.io.FileOutputStream
fun copyAssetDir(context: Context, assetPath: String, destDirPath: String) {
walkAssetDir(context, assetPath) {
copyAssetFile(context, it, "$destDirPath/$it")
}
}
fun walkAssetDir(context: Context, assetPath: String, callback: ((String) -> Unit)) {
val children = context.assets.list(assetPath) ?: return
if (children.isEmpty()) {
callback(assetPath)
} else {
for (child in children) {
walkAssetDir(context, "$assetPath/$child", callback)
}
}
}
fun copyAssetFile(context: Context, assetPath: String, destPath: String): File {
val destFile = File(destPath)
File(destFile.parent).mkdirs()
destFile.createNewFile()
context.assets.open(assetPath).use { src ->
FileOutputStream(destFile).use { dest ->
src.copyTo(dest)
}
}
return destFile
}
This is code for copy assets folder with directory and files both copy into sdcard folder...
this one works perfectly for me...
public 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());
}
}
My app uses the following piece of code to write out images I have resized into the app's data folder:
private void writeImage(Bitmap bmp, String filename)
{
try
{
FileOutputStream stream = openFileOutput(filename, MODE_WORLD_WRITEABLE);
bmp.compress(CompressFormat.PNG, 100, stream);
stream.flush();
stream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I am able to read them in a file browser (ddms) and can confirm they appear to have been written.
However, any attempt to load the images results in non-null bitmaps with width and height of -1. I am using the following code to load them:
imageList = getFilesDir().list();
Bitmap bmp = null;
for(String img : imageList)
{
try {
bmp = BitmapFactory.decodeStream(openFileInput(img));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT: On further inspection, it seems, after conversion the images are of density 160 (and not 240 as they should be) also, after testing a working application it seems the -1 mWidth and -1 mHeight on the bitmaps is irrelevent.
I had same problem.my data folder given smallest image.and cursor return null pointer exception on my getDestination method.then i fixed like it
public void captureNewPhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
targetFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
targetUri = Uri.fromFile(targetFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 12);
}
And i use like in onActivityResult();
BitmapFactory.Options options = new BitmapFactory.Options();
networkBitmap = BitmapFactory.decodeFile(targetUri.getPath(),
options);
//ImageDialog(networkBitmap);
//String path = getRealPathFromUri(this, Uri.parse(targetUri.getPath()));
String myDeviceModel = android.os.Build.MODEL;
deviceName = Build.MANUFACTURER;
if (myDeviceModel.equals("GT-I9500")) {
} else if (deviceName.contains("samsung")) {
} else {
exif = ReadExif(targetUri.getPath());
if (exif.equals("6")) {
matrixx.postRotate(90);
} else if (exif.equals("7")) {
matrixx.postRotate(-90);
} else if (exif.equals("8")) {
matrixx.postRotate(-90);
} else if (exif.equals("5")) {
matrixx.postRotate(-90);
}
//matrixx.postRotate(-90);
}
networkBitmap = Bitmap.createBitmap(networkBitmap, 0, 0, networkBitmap.getWidth(), networkBitmap.getHeight(), matrixx, true);
Log.e("Taget File ", "Size " + targetFile.length());
if (networkBitmap != null) {
ImageSetting(networkBitmap, System.currentTimeMillis() + filename);
}
public void ImageSetting(Bitmap imageBitmap, final String fileName) {
networkBitmap = imageBitmap;
organizator(networkBitmap, fileName);
networkBitmap = null;
}` public void tamamlandiOndenFoto(Bitmap turnedBitmap, String filename) {
frontFotoFile = storeBitmap(networkBitmap, filename);
ondenFotoPath = ondenFoto.getAbsolutePath();
ondenFotoImageView.setImageBitmap(turnedBitmap);
}`
public File storeBitmap(Bitmap bp, String fileName) {
File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File dest = new File(sd, fileName);
if (bp != null) {
try {
FileOutputStream out = new FileOutputStream(dest);
bp.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Alinan hata ", " Catch hata ", e);
}
return dest;
} else {
return null;
}
}
I hope give you any idea for your problem.