Как скопировать изображение на SD-карту в Android - PullRequest
1 голос
/ 29 ноября 2011

Как скопировать песни или изображения на мою SD-карту.т.е. скачать образ и сохранить на SD-карту в Android.

Спасибо, Shiv

Ответы [ 4 ]

1 голос
/ 29 ноября 2011

Попробуйте этот код:

File src = new File(Your_current_file);
File dest = new File(destination_place);

    public void copyFile(File src, File dest) throws IOException
    {
      InputStream in = new FileInputStream(src);
      OutputStream out = new FileOutputStream(dest);

    // 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();
    }

Обязательно дайте разрешение на внешнее хранилище, если вам нужно:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Надеюсь, это поможет вам.

0 голосов
/ 29 ноября 2011
private final String PATH = "/data/data/com.whatever.whatever/";  //put the downloaded file here


public void DownloadFromUrl(String imageURL, String fileName) {  //this is the downloader method
        try {
                URL url = new URL("http://yoursite.com/&quot; + imageURL); //you can write here any link
                File file = new File(fileName);

                long startTime = System.currentTimeMillis();
                Log.d("ImageManager", "download begining");
                Log.d("ImageManager", "download url:" + url);
                Log.d("ImageManager", "downloaded file name:" + fileName);
                /* Open a connection to that URL. */
                URLConnection ucon = url.openConnection();

                /*
                 * Define InputStreams to read from the URLConnection.
                 */
                InputStream is = ucon.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);

                /*
                 * Read bytes to the Buffer until there is nothing more to read(-1).
                 */
                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                int current = 0;
                while ((current = bis.read()) != -1) {
                        baf.append((byte) current);
                }

                /* Convert the Bytes read to a String. */
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baf.toByteArray());
                fos.close();
                Log.d("ImageManager", "download ready in"
                                + ((System.currentTimeMillis() - startTime) / 1000)
                                + " sec");

        } catch (IOException e) {
                Log.d("ImageManager", "Error: " + e);
        }

}

И не забудьте добавить следующие разрешения:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
0 голосов
/ 29 ноября 2011
File path = Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");

try {
    // Make sure the Pictures directory exists.
    path.mkdirs();

    // Very simple code to copy a picture from the application's
    // resource into the external file.  Note that this code does
    // no error checking, and assumes the picture is small (does not
    // try to copy it in chunks).  Note that if external storage is
    // not currently mounted this will silently fail.

    InputStream is = //Input stream of the file downloaded;
    OutputStream os = new FileOutputStream(file);
    byte[] data = new byte[is.available()];
    is.read(data);
    os.write(data);
    is.close();
    os.close();

    // Tell the media scanner about the new file so that it is
    // immediately available to the user.
    MediaScannerConnection.scanFile(this,
            new String[] { file.toString() }, null,
            new MediaScannerConnection.OnScanCompletedListener() {
        public void onScanCompleted(String path, Uri uri) {
            Log.i("ExternalStorage", "Scanned " + path + ":");
            Log.i("ExternalStorage", "-> uri=" + uri);
        }
    });
} catch (IOException e) {
    // Unable to create file, likely because external storage is
    // not currently mounted.
    Log.w("ExternalStorage", "Error writing " + file, e);
}
0 голосов
/ 29 ноября 2011
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdcard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");

FileOutputStream f = new FileOutputStream(file);

Не забудьте добавить разрешение:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...