无法在Android中的外部存储中写入文件

时间:2012-05-02 17:33:16

标签: android

请检查以下代码。 我无法将资源文件复制到Android手机中的外部存储器。 虽然,我能够使用我评论的代码进行复制,但我想知道原始代码的问题。

public class ExternalData extends Activity implements OnItemSelectedListener,
    OnClickListener {

TextView canRead = null;
TextView canWrite = null;
String state = null;
boolean canR, canW;

EditText userEnteredFileName;
Button bConfirm, bSaveAs;

Spinner spinner = null;
String[] stuff = { "Music", "Pictures", "Downloads" };
File path = null;
File file = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.externaldata);

    canRead = (TextView) findViewById(R.id.tvCanRead);
    canWrite = (TextView) findViewById(R.id.tvCanWrite);

    userEnteredFileName = (EditText) findViewById(R.id.etUserEnteredFileName);
    bConfirm = (Button) findViewById(R.id.bConfirm);
    bSaveAs = (Button) findViewById(R.id.bSaveAs);

    bConfirm.setOnClickListener(this);
    bSaveAs.setOnClickListener(this);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, stuff);
    spinner = (Spinner) findViewById(R.id.spinner1);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

}

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {

    int position = spinner.getSelectedItemPosition();
    switch (position) {
    case 0:
        path = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
        break;
    case 1:
        path = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        break;
    case 2:
        path = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        break;
    }
}

public void checkState() {

    state = Environment.getExternalStorageState();
    if (state.equals(Environment.MEDIA_MOUNTED)) {
        canRead.setText("Can Read: true");
        canWrite.setText("Can Write: true");
        canR = canW = true;
    } else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
        canRead.setText("Can Read: true");
        canWrite.setText("Can Write: false");
        canR = true;
        canW = false;
    } else {
        canRead.setText("Can Read: false");
        canWrite.setText("Can Write: false");
        canR = canW = false;
    }
}

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    switch (arg0.getId()) {
    case R.id.bConfirm:
        bSaveAs.setVisibility(View.VISIBLE);
        break;
    case R.id.bSaveAs:
        checkState();
        if(canR == canW == true){

            file = new File (path, userEnteredFileName.getText().toString() + "/");


            try {
                if(!file.exists()){
                    boolean success = file.mkdirs();
                    if(success){
                        Toast.makeText(ExternalData.this, "File created", Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(ExternalData.this, "Not able to create file", Toast.LENGTH_LONG).show();
                    }
                }
                InputStream fis = getResources().openRawResource(R.drawable.darthvader);
                /* this works....but wats wrong with the original code
                file = new File(file, "darthVader.png");
                if(!file.exists()){
                    file.createNewFile();
                }
                */
                FileOutputStream fos = new FileOutputStream(file);
                byte[] data = new byte[fis.available()];
                fis.read(data);
                fos.write(data);
                fis.close();
                fos.close();

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                Toast.makeText(ExternalData.this, "FilNOT", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Toast.makeText(ExternalData.this, "IO", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }
        break;
    }
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}

}

2 个答案:

答案 0 :(得分:1)

您是否在清单中申请了许可?

&lt; uses-permission android:name =“android.permission.WRITE_EXTERNAL_STORAGE”/&gt;

答案 1 :(得分:0)

请参阅this示例,了解如何在sdcard(外部存储)中写入文件

        InputStream input;
        try {
            URL url = new URL (strURL);
            input = url.openStream();
            byte[] buffer = new byte[1500];
            OutputStream output = new FileOutputStream ("/sdcard/"+pos+".png");


                int bytesRead = 0;
                while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
                {
                    output.write(buffer, 0, bytesRead);
                }

            finally
            {
                output.close();
                buffer=null;
            }

不要忘记在表现文件中给予许可

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