2010-11-01 117 views
0

我的应用程序是联系人列表,我想存储在SD卡 我的联系人数据,但我怎么可以存储在SD卡中的数据,或者如果我将使用数据库的话,我要如何存储它或使用简单的文件比我要如何保存它如何在SD卡写入数据

thanx提前

回答

1

如果你真的想要一个简单的文件存储到SD卡上,你可以像这样:

File sdCard = Environment.getExternalStorageDirectory(); // get a handle to the SD card 
File myFile = new File(sdCard, "test"); // get a file handle so a single file 

现在你可以使用一个BufferedWriter,例如,或任何其他Java方法写入该新文件。

您的应用程序应该写入SD卡,当然,加入WRITE_EXTERNAL_STORAGE的权限。

按照惯例,所有应用程序数据应该存储在SD卡上的以下目录:Android/data/your.package.name/files/

另外请注意,你应该明确地检查SD卡是否实际存在,或者如果它的可写,等等。有关文档,请参阅here

1

可以使用Environment.getExternalStorageDirectory()获取路径,然后使用这个路径打开一个文件。

您可能需要具备以下权限集:使用下面的代码

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 
0

存储联系人数据到设备的SD卡。

VCardActivity.java:-

public class VCardActivity extends Activity { 
     Cursor cursor; 
     ArrayList<String> vCard; 
     String vfile; 
     static Context mContext; 

     /** Called when the activity is first created. */ 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
      mContext = VCardActivity.this; 
      getVCF(); 
     } 

     public static void getVCF() { 
      final String vfile = "Contacts.vcf"; 
      Cursor phones = mContext.getContentResolver().query(
      ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
            null, null, null); 
      phones.moveToFirst(); 
      for (int i = 0; i < phones.getCount(); i++) { 
        String lookupKey = phones.getString(phones 
          .getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); 
        Uri uri = Uri.withAppendedPath(
        ContactsContract.Contacts.CONTENT_VCARD_URI, 
               lookupKey); 
        AssetFileDescriptor fd; 
        try { 
          fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r"); 
          FileInputStream fis = fd.createInputStream(); 
          byte[] buf = new byte[(int) fd.getDeclaredLength()]; 
          fis.read(buf); 
          String VCard = new String(buf); 
          String path = Environment.getExternalStorageDirectory() 
            .toString() + File.separator + vfile; 
          FileOutputStream mFileOutputStream = new FileOutputStream(path, 
            true); 
          mFileOutputStream.write(VCard.toString().getBytes()); 
          phones.moveToNext(); 
          Log.d("Vcard", VCard); 
        } catch (Exception e1) { 
          // TODO Auto-generated catch block 
          e1.printStackTrace(); 
        } 
      } 
     } 
} 

,看看下面的链接了解更多信息。

Export Contacts as a VCF file

并在下面给出权限到您的AndroidManifest.xml文件。

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