允许在 SD 卡上写入 android [英] Permission to write on SD card android

查看:19
本文介绍了允许在 SD 卡上写入 android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写入 SD 卡时遇到问题,这是代码:(抱歉代码的排版,直接复制粘贴了)

I have a problem writing to the SD card, here is the code: (Sorry about the layout of the code, just copy pased it )

public class SaveAndReadManager {

 private String result;
 private String saveFileName = "eventlist_savefile";

 public String writeToFile( ArrayList<Event> arrlEvents ){
  FileOutputStream fos = null;
  ObjectOutputStream out = null;

  try{
   File root = Environment.getExternalStorageDirectory();

   if( root.canWrite() ){
    fos = new FileOutputStream( saveFileName );
    out = new ObjectOutputStream( fos );
    out.writeObject( arrlEvents );

    result = "File written";

    out.close();
   }else{
    result = "file cant write";
   }
  }catch( IOException e ){
   e.printStackTrace();
   result = "file not written";
  }

  return result;
 }

 public boolean readFromFile(){
  return false;
 }
}

我还没有实现 readFromFile() .问题是 root.canWrite() 一直返回 false.这是清单文件:

I have not implemented the readFromFile() yet. The problem is that root.canWrite() returns false all the time. Here is the manifest file:

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

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".InfoScreen"
           android:label="@string/app_name">
      <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    <activity android:name=".EventCalendar"
              android:label="@string/app_name" />

    <activity android:name=".MakeEvent"
              android:label="@string/app_name" />

    <activity android:name=".ViewEvent"
              android:label="@string/app_name" />

</application>
<uses-sdk android:minSdkVersion="8" />

我已经申请了写入权限,在我的 avd 上,如果我进入设置 -> SD 卡和手机存储,它会告诉我 SD 卡上有 1 GB 可以写入.请帮忙.

I've asked for the permission to write, and on my avd, if i go to settings -> SD card and phone storage, it tells me i have 1 gb on the sd card to write on. Please help.

谢谢:)

推荐答案

您看到从 writeToFile 返回的哪个结果?文件未写入"或文件无法写入"?

Which result are you seeing retunred from writeToFile? "file not written" or "file cant write"?

当我运行您的代码时,它掉入了 catch IOException 块,结果是文件未写入".原因是 fos 定义不正确:

When I ran your code it dropped into the catch IOException block with the result of "file not written". The reason for this was that fos was defined incorrectly:

fos = new FileOutputStream( saveFileName );

应该是:

fos = new FileOutputStream( root + "/" saveFileName );

更改这一行后,我得到了从 writeToFile 返回的结果已写入文件".

After I changed this line, I got the result "File written" returned from writeToFile.

这篇关于允许在 SD 卡上写入 android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆