android:- how to copy image from Assets to SD Card? - android

I have some images to be displayed in the Application (When user selects an image from it, like picking from gallery ).
The question is how to copy the images I am putting in the assets
folder in the code to a folder on the SD card.
Edit: I tried this example : http://www.technotalkative.com/android-copy-files-from-assets-to-sd-card/
I have given the app permission to read and write
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

AssetManager assetManager = context.getAssets();
InputStream is = assetManager.open(fileName);
Get the AssetManager and call open with the filename you want to copy as parameter.
Then you can simply copy in this way
File out = new File(Environment.getExternalStorageDirectory(), fileName);
byte[] buffer = new byte[BUFFER_LEN];
FileOutputStream fos = new FileOutputStream(out);
int read = 0;
while ((read = is.read(buffer, 0, BUFFER_LEN)) >= 0) {
fos.write(buffer, 0, read);
}
fos.flush();
fos.close()
is.close()
remember to add the WRITE_EXTERNAL_STORAGE permission in your AndroidManifest.xml file

private void copyFileAssets() {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("ceo.jpg");
out = new FileOutputStream(Environment.getExternalStorageDirectory()+File.separator+ "abc.jpg");
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
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);
}
}
you have to add this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Get the bitmap resource using one of the many ways.
Ex:
Bitmap bitmap = BitmapFactory.decodeResource(resource, id); // get your bitmap that you want to save on SD card.
Get the path to store the resource.
String compressedFilePath = Environment.getExternalStorageDirectory() + File.separator + "FOLDERNAME" + File.separator + "FILENAME.jpg";
Save using compress method. (Shortcut way to save image as per docs)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(pathToStore))); // use 100 to make sure image quality is not reduced(Read the docs)
Note: You need Write(and may be read in future) access to write to SDCARD.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Related

Copying file from raw to external storage

Trying to copy a PDF file (template) to a custom directory in the external storage (non-sd card).
public void copyPDFToExternal(String newFileName) throws IOException {
// Create directory folder if it doesnt exist.
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "pdfFolder");
if (!folder.exists()){
folder.mkdir();
}
// Copy template
InputStream in = getResources().openRawResource(R.raw.pdf_template);
FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() +
File.separator + "pdfFolder/"+newFileName+".pdf");
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0 ) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
}
I have added the following to AndroidManifest.xml, not in the application tag.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Full error: http://pastebin.com/TBtbekiB
If you need me to post anything else let me know.
Where have I gone wrong?
Update: No longer crashes but now doesn't seem to do anything... the mkdirs returns true.
public void copyPDFToExternal(String newFileName) throws IOException {
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/test/");
if (!folder.exists()){
if (!folder.mkdirs()){
eme.setText("Failed");
return;
};
}
InputStream in = getResources().openRawResource(R.raw.ohat);
FileOutputStream out = new FileOutputStream(folder.getAbsolutePath() +"/"+newFileName+".pdf");
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0 ) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
}
I've also added a permission request, this is a little long so using pastebin.
http://pastebin.com/KgivWNuc
Edit 2:
So it seems it does work, just the directory cannot be see when the device is connected to a computer (in MTP mode). But I guess that's another issue.
if you are installing in device os version android M and more you need to take permission at runtime. Adding in manifest alone is not sufficient. Refer this for more details.
Can you specify which external storage you are using as you have said it is (non SD Card) because if you are using Environment.getExternalStorageDirectory() then it will give you the path of SD Card Storage, something like this /storage/emulated/0/ where 0 represents primary storage device.

can't create folder on externalstorage

I'm trying to create a folder on external storage with no success.Although i've managed to create a folder in my app's directory, i can't do the same for external storage and i also get false when i call canWrite().I have declared the WRITE_EXTERNAL_PERMISSION on manifest.
Here is my code for my app's directory
File file1=new File(context.getFilesDir(), "//test1");
file1.mkdir();
System.out.println(file1.canWrite());
and for ExternalStorage respectively
File file2=new File(Environment.getExternalStorageDirectory(), "//test2");
file2.mkdir();
System.out.println(file2.canWrite());
In the first case the folder gets created and i get true on println.On the second one folder does not get created and i get false on println.
Add Below Permission i your manifest.xml
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
String PATH = Environment.getExternalStorageDirectory() + "/download/YourPath";
String fileName="Name for your File";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
This will create a directory,if you use comma,it means "//test2" will become a file name
String string = Environment.getExternalStorageDirectory().getPath() + "/test2";
File file = new File(string, "file_name");
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(your_data);
fileOutputStream.flush();
fileOutputStream.close();

mp3 not saving to sd correctly; how to save mp3 to sd card?

I've been looking at this site for the past 3 or so hours. How to copy files from 'assets' folder to sdcard?
This is the best I could come up with because I'm only trying to copy one file at a time.
InputStream in = null;
OutputStream out = null;
public void copyAssets() {
try {
in = getAssets().open("aabbccdd.mp3");
File outFile = new File(root.getAbsolutePath() + "/testf0lder");
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: ", e);
}
}
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);
}
}
I've figured out how to create a file and save a text file. http://eagle.phys.utk.edu/guidry/android/writeSD.html
I would rather save an mp3 file to the sdcard rather than a text file.
When I use this code I provided, I get a text document that same size as the aabbccdd.mp3 file. It does not create a folder and save an .mp3 file. It saves a text document in the root folder. When you open it, I see a whole bunch of chinese letters, but at the top in English I can see the words WireTap. WireTap Pro was the program I used to record the sound so I know the .mp3 is passing through. It's just not creating a folder and then saving a file like the above .edu example.
What should I do?
I think you should do something like that -[Note: this i used for some other formats not mp3 but its works on my app for multiple format so i hope it will work for u too.]
InputStream in = this.getAssets().open("tmp.mp3"); //give path as per ur app
byte[] data = getByteData(in);
Make sure u have the folder already exists on path, if folder is not there it will not save content correctly.
byteArrayToFile(data , "testfolder/tmp.mp3"); //as per ur sdcard path, modify it.
Now the methods ::
1) getByteData from inputstream -
private byte[] getByteData(InputStream is)
{
byte[] buffer= new byte[1024]; /* or some other number */
int numRead;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try{
while((numRead = is.read(buffer)) > 0) {
bytes.write(buffer, 0, numRead);
}
return bytes.toByteArray();
}
catch(Exception e)
{ e.printStackTrace(); }
return new byte[0];
}
2) byteArrayToFile
public void byteArrayToFile(byte[] byteArray, String outFilePath){
FileOutputStream fos;
try {
fos = new FileOutputStream(outFilePath);
fos.write(byteArray);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Android - Copy res/raw resource to SD correctly

Well, I tried a lot of things, but the better goal that I achieve is copy the desired file to sd, but the new file size is 0bytes always :(
This is my code :
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = sonidoActual+".mp3";
File newSoundFile = new File(baseDir, fileName);
Uri mUri = Uri.parse("android.resource://com.genaut.ringtonelists/raw/"+sonidoActual);
AssetFileDescriptor soundFile;
try {
soundFile= getContentResolver().openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile=null;
}
try {
byte[] readData = new byte[1024*500];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
Log.d("Degug - While: ", "i: "+i);
}
fos.flush();
fos.close();
} catch (IOException io) {
}
Sorry for my bad english.Any one know the problem? Thanks a lot!
I have these permissions on my manifest:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
More info:
I tried some code to copy files from assets and not work.. I have some app that set Ringtone well, so I don't think that my SD has a problem.. I feel hopeless :S
These are the code from assets, apparently works fine: https://stackoverflow.com/a/4530294/1422434
I tried too with getResources.openRawResource(): but not works
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = nombreActual+".mp3";
File newSoundFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024*500];
InputStream fis = getResources().openRawResource(contexto.getResources().getIdentifier(sonidoActual,"raw", contexto.getPackageName()));
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
As you are using the raw folder, simply use this from your activity:
getResources().openRawResource(resourceName)

How to create a independent and full copy of a File object?

Official facebook App has a bug, when you try to share an image with share intent, the image gets deleted from the sdcard. This is the way you have to pass the image to facebook app using the uri of the image:
File myFile= new File(Environment.getExternalStorageDirectory(), "car.jpg");
Uri uri = Uri.fromFile(myFile);
i.putExtra(Intent.EXTRA_STREAM, uri);
Then, suppose that if i create a copy from the original myFile object, and i pass the uri of the copy to facebook app, then, my original image will not be deleted.
I tried with this code, but it doesn't work, the original image file is still getting deleted:
File myFile= new File(Environment.getExternalStorageDirectory(), "car.jpg");
File auxFile=myFile.getAbsoluteFile();
Uri uri = Uri.fromFile(auxFile);
Can someone tell me how to do a exact copy of a file that doesn't redirect to the original File?
Please check: Android file copy
The file is copied byte by byte so no reference to the old file is maintained.
Here, this should be able to create a copy of your file:
private void CopyFile() {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(<file path>);
out = new FileOutputStream(<output path>);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
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);
}
}

Categories

Resources