Android的加载本地XML文件 [英] Android load local xml file

查看:417
本文介绍了Android的加载本地XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与Eclipse的工作。有谁知道这片code的尝试从该文件?
我复制我的文件到项目文件夹,也对SRR / package_path文件夹中。

公共字符串getFromFile(ASerializer aserializer){
    字符串数据=新的String();
    尝试{
    的FileInputStream流=新的FileInputStream(新文件(aserializer.toLocalResource()));
       FileChannel FC = stream.getChannel();
        MappedByteBuffer BB = fc.map(FileChannel.MapMode.READ_ONLY,0,fc.size());
        / *而不是使用默认的,通过在德$ C $铬。 * /
        。数据= Charset.defaultCharset()德code(BB)的ToString();
        stream.close();
    }
    赶上(例外五){
        数据=找不到文件;
    }
    返回的数据;
}


解决方案

这code,因为它的使用的FileInputStream 的,会间preT的文件路径为整个Android的文件系统上的文件的路径。也就是说,文件系统的根目录将在整个Android系统的所在,而不是某个应用程序中的资源在文件系统的根目录。

如果您想根据文件名从应用程序资源加载文件,可以把文件可以在您的Eclipse应用程序项目的'资产'目录,然后使用:

 的InputStream的InputStream = getResources()getAssets()开(file.xml)。;

要获得的InputStream 文件一起工作的。给<一个路径href=\"http://developer.android.com/reference/android/content/res/AssetManager.html#open%28java.lang.String%29\"相对=nofollow> AssetManager.open()是相对于资产目录。您也可以组织在子目录的文件:

 的InputStream的InputStream = getResources()getAssets()开(子目录/ file.xml)。;

I'm working with Eclipse. Does anybody know where this piece of code tries to get the file from? I've copied my files to the project folder and also the srr/package_path folder.

public String getFromFile(ASerializer aserializer) {
    String data = new String();
    try {
    FileInputStream stream = new FileInputStream(new File(aserializer.toLocalResource()));
       FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        /* Instead of using default, pass in a decoder. */
        data  = Charset.defaultCharset().decode(bb).toString();
        stream.close();
    }
    catch (Exception e){
        data = "File not found";
    }
    return data;
}

解决方案

That code, because of its use of FileInputStream, will interpret the file path as a path to a file on the whole Android file system. That is, the file system root will be the root of the file system in which the whole Android system resides rather than somewhere in your application resources.

If you want to load files from your application resources based on file name, you can put the files in the 'assets' directory of your Eclipse application project and then use:

InputStream inputStream = getResources().getAssets().open("file.xml");

to get an InputStream of the file to work with. The path given to AssetManager.open() is relative to the 'assets' directory. You can also organize files in sub directories:

InputStream inputStream = getResources().getAssets().open("subdirectory/file.xml");

这篇关于Android的加载本地XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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