【问题标题】:Copying Xml File From Res/Xml Folder to Device Storage将 Xml 文件从 Res/Xml 文件夹复制到设备存储
【发布时间】:2011-11-15 08:18:30
【问题描述】:

我正在尝试将一个 xml 文件从 res/xml 文件夹复制到设备存储中,但我真的很难做到这一点。

我知道起点是获取InputStream 来读取xml 文件。这是通过使用这个来实现的:

InputStream is = getResources().openRawResource(R.xml.xmlfile);

最终输出流将是:

file = new File("xmlfile.xml");
FileOutputStream fileOutputStream = new FileOutputStream(file);

但我真的很纠结如何正确准确地读取和复制初始 xml 文件中的所有信息。

到目前为止,我已经尝试过使用各种InputStream 和OutputStream 进行读写(DataInputStream、DataOutputStream、OutputStreamWriter 等),但我仍然没有正确地得到它.生成的 xml 文件中有一些未知字符(编码问题?)。谁可以帮我这个事?谢谢!

【问题讨论】:

    标签: android xml inputstream outputstream


    【解决方案1】:

    从res/xml 你不能把所有文件放在你的assets 文件夹中然后使用下面的代码

    Resources r = getResources();
    AssetManager assetManager = r.getAssets();
    
    File f = new File(Environment.getExternalStorageDirectory(), "dummy.xml");
    InputStream is = = assetManager.open("fileinAssestFolder.xml");
    OutputStream os = new FileOutputStream(f, true);
    
    final int buffer_size = 1024 * 1024;
    try
    {
        byte[] bytes = new byte[buffer_size];
        for (;;)
        {
            int count = is.read(bytes, 0, buffer_size);
            if (count == -1)
                break;
            os.write(bytes, 0, count);
        }
        is.close();
        os.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
    

    【讨论】:

    • 它工作,部分...你能解释一下为什么这样的buffer_size吗?你能详细说明for循环吗?我尝试过使用您的方法和其他一些方法,但似乎新创建的 xml 要么更短,要么更长。我仍然不确定为什么我无法获得与原始完全相同的 xml。
    【解决方案2】:

    我认为您应该改用 raw 文件夹。看看http://developer.android.com/guide/topics/resources/providing-resources.html。

    【讨论】:

    • 是的,raw 和 assets 文件夹(正如 ingsaurabh 之前所建议的)都可以正常工作。但我还有另一个问题(正如我在 ingsaurabh 的帖子中评论的那样),也许你也可以帮忙?
    【解决方案3】:

    您也可以使用此代码:

       try {
            InputStream input = getResources().openRawResource(R.raw.XZY);
            OutputStream output = getApplicationContext().openFileOutput("xyz.mp3", Context.MODE_PRIVATE);
            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
        }
    

    当您需要文件时,请使用以下代码:

    File k =getApplicationContext().getFileStreamPath("xyz.mp3");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 2023-01-20
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      相关资源
      最近更新 更多