簡體   English   中英

如何訪問/讀取/寫入Android設備上內部存儲中的Documents文件夾?

[英]How do I access/read from/write to Documents folder in Internal Storage on Android devices?

如何訪問Android手機內部存儲空間中的公共文檔文件夾? 我需要讀取和寫入可公開訪問的文件到Documents文件夾中。

好吧,我自己解決了這個問題:)

它與普通Windows桌面應用程序的操作非常相似:

從Documents文件夾創建和讀取文件(在Android設備上):

string content = "Jason rules";
string filename = "file.txt";

var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
if (!Directory.Exists(documents))
{
    Console.WriteLine("Directory does not exist.");
}
else
{
    Console.WriteLine("Directory exists.");

    File.WriteAllText(documents + @"/" + filename, content);

    if (!File.Exists(documents + @"/" + filename))
    {
        Console.WriteLine("Document not found.");
    }
    else
    {
        string newContent = File.ReadAllText(documents + @"/" + filename);

        TextView viewer = FindViewById<TextView>(Resource.Id.textView1);
        if (viewer != null)
        {
            viewer.Text = newContent;
        }
    }
}

完整樣本:

using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace ToolbarSample
{
    [Activity(Label = "ToolbarSample", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.button);

            if (button != null)
            {
                button.Click += delegate
                {
                        button.Enabled = false;

                        string content = "Jason rules";
                        string filename = "file.txt";

                        var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
                        if (!Directory.Exists(documents))
                        {
                            Console.WriteLine("Directory does not exist.");
                        }
                        else
                        {
                            Console.WriteLine("Directory exists.");

                            File.WriteAllText(documents + @"/" + filename, content);

                            if (!File.Exists(documents + @"/" + filename))
                            {
                                Console.WriteLine("Document not found.");
                            }
                            else
                            {
                                string newContent = File.ReadAllText(documents + @"/" + filename);

                                TextView viewer = FindViewById<TextView>(Resource.Id.textView1);
                                if (viewer != null)
                                {
                                    viewer.Text = newContent;
                                }
                            }
                        }
                };
            }
        }
    }
}

不要忘記向androidmanifest.xml添加權限

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

寫作的樣本

        // write on SD card file data in the text box
        try {
            File myFile = new File("/sdcard/mysdfile.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = 
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(txtData.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Done writing SD 'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

閱讀樣本

         try {
            File myFile = new File("/sdcard/mysdfile.txt");
            FileInputStream fIn = new FileInputStream(myFile);
            BufferedReader myReader = new BufferedReader(
                    new InputStreamReader(fIn));
            String aDataRow = "";
            String aBuffer = "";
            while ((aDataRow = myReader.readLine()) != null) {
                aBuffer += aDataRow + "\n";
            }
            txtData.setText(aBuffer);
            myReader.close();
            Toast.makeText(getBaseContext(),
                    "Done reading SD 'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

有了讀取外部存儲的權限,此代碼應該適合您。

var path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments);

var filename = System.IO.Path.Combine(path.ToString(), strFile);

System.IO.FileStream fs = new FileStream(filename, FileMode.Open);

byData = new byte[fs.Length];

fs.Read(byData, 0, (int)fs.Length);
fs.Close();

如果你運行的sdk高於23,android版本高於6,你應該實現對用戶的訪問請求。 請在鏈接中找到更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM