Copy image from raw folder to external sd card? - android

I use this code but it fails at the file outputstream.
When i make a static void then getResources will fail.
public void copy (Context context) {
InputStream in = getResources().openRawResource(R.raw.high1);
FileOutputStream out = new FileOutputStream("/sdcard/pic1.jpg");
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();
}
}

To getResources() do not fail when changing it to static, modify the line:
InputStream in = getResources().openRawResource(R.raw.high1);
To:
InputStream in = context.getResources().openRawResource(R.raw.high1);
Additionally, quoting CommonsWare:
NEVER HARDCODE PATHS. Use getExternalFilesDir(), or Environment.getExternalStoragePublicDirectory(), or something like that to get a directory on external storage to use.

Related

Copying file (img/doc) from a specific path to another in Android

I've a functionality in my application in which I save a doc/img file path in my database. This file is lying in a folder (E.g. "/mnt/sdcard/MyApp/MyItem/test.png"). Now what i want to do is to copy this file to other folder (E.g. /mnt/sdcard/MyApp/MyItem/Today/test.png).
Right now I am using the code below but it's not working :
private void copyDirectory(File from, File to) throws IOException {
try {
int bytesum = 0;
int byteread = 0;
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
} catch (Exception e) {
}
}
and on button click am using the following code :
File sourceFile = new File(fileList.get(0).getAbsolutePath); //comes from dbs
File targetFile = new File(Environment.getExternalStorageDirectory(),"MyApp/MyItem/Today/");
copyDirectory(sourceFile,targetFile, currDateStr);
Any idea why it's not working?
This code is working fine for me.
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
And one more thing have you added in Manifest file *permission to write to external storage.*
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Yup got it working, I was not giving file name while copying the files, and didnt really look at error log, got it working now thanks. And yea the above code works just fine.

Save Bitmap From ZipinputStream Directly to File

I have a zip file which I'm listing and sorting each file inside by iterating through the stream using zis.getNextEntry().
Works fine for getting String objects from the ZipEntry, what I need is to save a copy to a directory in my application.
The directory part I'm fine with I just need to know how to save each bitmap straight away, without necessarily decoding it and creating a Bitmap object in memory.
This is my code to get each of the text file's contents.
if (decodeFile) { // WE ARE LOOKING AT A FILE WE CAN DECODE
while ((read = zis.read(buffer, 0, 1024)) >= 0) {
String string = new String(buffer, 0, read);
s.append(string);
}
stringArray.add(s.toString());
} else { // WE ARE LOOKING AT AN IMAGE/DIRECTORY
}
Thanks in advance.
if (decodeFile) { // WE ARE LOOKING AT A FILE WE CAN DECODE
FileWriter fw = new FileWriter("path/name.ext");
while ((read = zis.read(buffer, 0, 1024)) >= 0) {
String string = new String(buffer, 0, read);
fw.write(string);
}
fw.close();
} else { // WE ARE LOOKING AT AN IMAGE/DIRECTORY
}
Maybe like so?
You should simply create an OutputStream and instead of reading values to String write them directly to the OutputStream.
It should be something like this:
ZipFile zipFile = new ZipFile("foo.zip");
InputStream in = null;
OutputStream out = new FileOutputStream("...");
in = zipFile.getInputStream(zipFile.getEntry("yourbitmap.jpg"));
byte data[] = new byte[1024];
while ((count = in.read(data, 0, 1024)) != -1) {
out.write(data, 0, count);
}

Android: how do I create File object from asset file?

I have a text file in the assets folder that I need to turn into a File object (not into InputStream). When I tried this, I got "no such file" exception:
String path = "file:///android_asset/datafile.txt";
URL url = new URL(path);
File file = new File(url.toURI()); // Get exception here
Can I modify this to get it to work?
By the way, I sort of tried to "code by example" looking at the following piece of code elsewhere in my project that references an HTML file in the assets folder
public static Dialog doDialog(final Context context) {
WebView wv = new WebView(context);
wv.loadUrl("file:///android_asset/help/index.html");
I do admit that I don't fully understand the above mechanism so it's possible that what I am trying to do can't work.
Thx!
You cannot get a File object directly from an asset, because the asset is not stored as a file. You will need to copy the asset to a file, then get a File object on your copy.
You cannot get a File object directly from an asset.
First, get an inputStream from your asset using for example AssetManager#open
Then copy the inputStream :
public static void writeBytesToFile(InputStream is, File file) throws IOException{
FileOutputStream fos = null;
try {
byte[] data = new byte[2048];
int nbread = 0;
fos = new FileOutputStream(file);
while((nbread=is.read(data))>-1){
fos.write(data,0,nbread);
}
}
catch (Exception ex) {
logger.error("Exception",ex);
}
finally{
if (fos!=null){
fos.close();
}
}
}
Contrary to what others say, you can obtain a File object from an asset as follows:
File myAsset = new File("android.resource://com.mycompany.app/assets/my-asset.txt");
This function missing in code. #wadali
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);
}
}
Source: https://stackoverflow.com/a/4530294/4933464

Android how to copy folder with files on it from Internal memory to External

I need to find a way how to create files from specific folder in Internal Storage of my device to a specific folder in External Storage.
Example :
I have 50 image files in data/data/app_package/files/documents/server/userId/storage/ in Internal Storage.
I want to copy all of the files in that directory to /sdcard/Documents/Server/UserId/Storage/
And the idea is that in some cases maybe I'll have to move files like 50MB and maybe more. Any suggestions how can I achieve this?
try this code
private void copyToFolder(String path) throws IOException {
File selectedImage = new File(path);
if (selectedImage.exists()) {
String wall = selectedImage.getName();
in = getContentResolver().openInputStream(selectedImageUri);
out = new FileOutputStream("/sdcard/wallpapers/" + wall);
copyFile( in , out); in .close(); in = null;
out.flush();
out.close();
out = null;
} else {
System.out.println("Does not exist");
}
}
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);
}
}

Copying Xml File From Res/Xml Folder to Device Storage

I'm trying to copy an xml file from the res/xml folder to the device storage but I'm really struggling on how to do this.
I know that the starting point is to get an InputStream to read the xml file. This is achieved by using this:
InputStream is = getResources().openRawResource(R.xml.xmlfile);
Eventually the output stream will be:
file = new File("xmlfile.xml");
FileOutputStream fileOutputStream = new FileOutputStream(file);
But I'm really struggling on how to read and copy all the information from the initial xml file correctly and accurately.
So far, I've tried using various InputStream and OutputStream to read and write (DataInputStream, DataOutputStream, OutputStreamWriter, etc.) but I still didn't managed to get it correctly. There are some unknown characters (encoding issue?) in the produced xml file. Can anyone help me on this? Thanks!
From res/xml you can't you have to put all files in your assets folder then use below code
Resources r = getResources();
AssetManager assetManager = r.getAssets();
File f = new File(Environment.getExternalStorageDirectory(), "dummy.xml");
InputStream is = = assetManager.open("fileinAssestFolder.xml");
OutputStream os = new FileOutputStream(f, true);
final int buffer_size = 1024 * 1024;
try
{
byte[] bytes = new byte[buffer_size];
for (;;)
{
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
is.close();
os.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
I think you should use the raw folder instead. Have a look at http://developer.android.com/guide/topics/resources/providing-resources.html.
You can also use this code:
try {
InputStream input = getResources().openRawResource(R.raw.XZY);
OutputStream output = getApplicationContext().openFileOutput("xyz.mp3", Context.MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
And when you need file use this code:
File k =getApplicationContext().getFileStreamPath("xyz.mp3");

Categories

Resources