Как сделать кнопку записи файла на SDCard? - PullRequest
0 голосов
/ 01 апреля 2012

В моем приложении мне нужна кнопка, которая при нажатии копирует файл, хранящийся в папке raw моих приложений, в sdcard / Android / data ..., перезаписывая уже существующий файл.

Вот что у меня есть. Файл в моей необработанной папке называется brawler.dat для примера.

Я не прошу никого писать весь код, но это наверняка будет бонусом.

Мне нужен в основном кто-то, чтобы указать мне правильное направление.

Я могу создавать кнопки для перехода по URL и т. Д., Но я чувствую, что готов к следующему уровню.

main.xml

 rLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Overwrite File" />

FreelineActivity.java

     package my.freeline.conquest;

import android.app.Activity;
import android.os.Bundle;

public class FreelineActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Ответы [ 2 ]

0 голосов
/ 01 апреля 2012

Вы можете сделать следующий простой вызов copyRawFile (). Подробнее о хранилище см. http://developer.android.com/guide/topics/data/data-storage.html

    private void copyRawFile() {


                InputStream in = null;
                OutputStream out = null;
    String filename="myFile"; //sd card file name           
    try {
//Provide the id of raw file to the openRawResource() method
                  in = getResources().openRawResource(R.raw.brawler);
                  out = new FileOutputStream("/sdcard/" + filename);
                  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);
            }
        }
0 голосов
/ 01 апреля 2012

Получите входной поток необработанных ресурсов следующим образом:

// in your activity in `onClick` event of the button:
InputStream is = getResources().openRawResource(R.raw.yourResourceName);

Затем прочитайте его в буфер и запишите в выходной поток файла:

OutputStream os = new FileOutputStream("real/path/name"); // you'll need WRITE_EXTERNAL_STORAGE permission for writing in external storage
byte[] buffer = new byte[1024];
int read = 0;
while ((read = is.read(buffer, 0, buffer.length)) > 0) {
  os.write(buffer, 0, size);
}
is.close();
os.close();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...