繁体   English   中英

如何使按钮将文件写入sdcard?

[英]How to make a button write a file to sdcard?

在我的应用程序中,我需要一个按钮,当按下该按钮时,会将存储在我的应用程序原始文件夹中的文件复制到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);
    }
}

通过这种方式获取原始资源输入流:

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

您可以执行以下简单的调用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);
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM