Android开发之资源文件存储

本文介绍在Android开发中关于资源文件的存储操作。

 

在android开发中,资源文件是我们使用频率最高的,无论是string,drawable,还是layout,这些资源都是我们经常使用到的,而且为我们的开始提供很多方便,不过我们平时接触的资源目录一般都是下面这三个。

/res/drawable 
/res/values 
/res/layout

 

除些之外,Android资源文件还有以下三种会经常使用到:

/res/xml  

/res/raw

/assets

 

首先是/res/xml ,这个目录中大家可能偶尔用到过,这里可以用来存储xml格式的文件,并且和其他资源文件一样,这里的资源是会被编译成二进制格式放到最终的安装包里的,我们也可以通过R类来访问这里的文件,并且解析里面的内容。 

 

例如我们在这里存放了一个名为file.xml的文件:

<? xml version="1.0" encoding="utf-8" ?> 
< book >
< title >XML高级编程 </ title >
</ book >  


  随后,我们就可以通过资源ID来访问并解析这个文件了,如下代码所示:

 

复制代码
     XmlResourceParser  xml = getResources().getXml(R.xml.file); 
    xml.next();
     int  eventType = xml.getEventType();
     boolean  inTitle =  false ;
     while (eventType != XmlPullParser.END_DOCUMENT) {
            
             // 到达title节点时标记一下
             if (eventType == XmlPullParser.START_TAG) {
                     if (xml.getName().equals("title")) {
                            inTitle =  true ;
                    }
            }
            
             // 如过到达标记的节点则取出内容
             if (eventType == XmlPullParser.TEXT && inTitle) {
                    ((TextView)findViewById(R.id.txXml)).setText(
                                    xml.getText()
                    );
            }
            
            xml.next();
            eventType = xml.getEventType();
    }
复制代码

 

在这里,我们用资源类的getXml方法,返回了一个xml解析器,这个解析器的工作原理和SAX方式差不多。

要注意的是,这里的xml文件,最终是会被编译成二进制形式的,如果大家想让文件原样存储的话,那么就要用到下一个目录啦,那就是/res/raw目录这个目录的唯一区别就是,这里的文件会原封不动的存储到设备上,不会被编译为二进制形式,访问的方式也是通过R类,下面是代码示例:


复制代码
    ((TextView)findViewById(R.id.txRaw) ).setText( readStream(getResources().openRawResource(R.raw.rawtext)) );
        
     private  String readStream(InputStream is) {
               
           try  {
                  ByteArrayOutputStream bo =  new  ByteArrayOutputStream();
                   int  i = is.read();
                   while (i != -1) {
                         bo.write(i);
                         i = is.read();
                  }
                        
                   return  bo.toString();
          }  catch  (IOException e) {
                   return  "";
          }
    }
复制代码

 

这次使用资源类中的方法,openRawResource,返回给我们一个输入流,这样我们就可以任意读取文件中的内容了,例如上面例子中那样,原样输出文本文件中的内容。

        
        当然,如果你需要更高的自由度,尽量不受android平台的约束,那么/assets这个目录就是我们的首选了。

 

        这个目录中的文件除了不会被编译成二进制形式之外,另外一点就是,访问方式是通过文件名,而不是资源ID。 并且还有更重要的一点就是,大家可以在这里任意的建立子目录,而/res目录中的资源文件是不能自行建立子目录的。如果需要这种灵活的资源存储方式,那么就看看下面这个例子:

 

    AssetManager assets = getAssets(); 
      ((TextView)findViewById(R.id.txAssets)).setText(readStream(assets.open("data.txt")));  


  在context上下文中,调用getAssets返回一个AssetManager,然后使用open方法就可以访问需要的资源了,这里open方法是以assets目录为根的。所以上面这段代码访问的是assets目录中名为data.txt的资源文件。

 

Android文件资源(raw/data/asset)的存取代码如下: 

一、私有文件夹下的文件存取(/data/data/包名)

 

复制代码
     import java.io.FileInputStream;   
    import java.io.FileOutputStream;  
     import org.apache.http.util.EncodingUtils;  
      
     public  void writeFileData(String fileName,String message){  
         try{  
         FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);  
          byte [] bytes = message.getBytes();  
         fout.write(bytes);  
          fout.close();  
         }  
         catch(Exception e){  
         e.printStackTrace();  
        }  
    }     
      
      
     public String readFileData(String fileName){  
         String res="";  
          try{  
          FileInputStream fin = openFileInput(fileName);  
           int length = fin.available();  
           byte [] buffer =  new  byte[length];  
          fin.read(buffer);      
          res = EncodingUtils.getString(buffer, "UTF-8");  
          fin.close();      
         }  
          catch(Exception e){  
          e.printStackTrace();  
         }  
          return res;  
        }    
复制代码

 

二、从resource中的raw文件夹中获取文件并读取数据(资源文件只能读不能写)

 

复制代码
     public  String getFromRaw(String fileName){   
        String res = "";  
        try{  
        InputStream in = getResources().openRawResource(R.raw.test1);   
         int length = in.available();        
         byte [] buffer =  new  byte[length];         
        in.read(buffer);          
        res = EncodingUtils.getString(buffer, "UTF-8");     
        in.close();             
       }  
        catch(Exception e){  
        e.printStackTrace();          
       }  
     return res ;  
   }  
复制代码

 

三、从asset中获取文件并读取数据(资源文件只能读不能写) 

 

复制代码
  public  String getFromAsset(String fileName){   
    String res="";  
     try{  
     InputStream in = getResources().getAssets().open(fileName);    
      int length = in.available();          
         byte [] buffer =  new  byte[length];         
        in.read(buffer);             
        res = EncodingUtils.getString(buffer, "UTF-8");      
    }  
     catch(Exception e){  
     e.printStackTrace();          
    }  
     return res;  
}
复制代码

 

关于Android获取assets的绝对路径有如下方法:

第一种方法:  

String path = "file:///android_asset/文件名";

第二种方法:

InputStream abpath = getClass().getResourceAsStream("/assets/文件名");

 

若要想要转换成String类型,则使用下列代码:

复制代码
       String path =  new  String(InputStreamToByte(abpath ));

     private  byte[] InputStreamToByte(InputStream is)  throws IOException {
        ByteArrayOutputStream bytestream =  new ByteArrayOutputStream();
         int ch;

         while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }

         byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
         return imgdata;
    }
复制代码

  

如果需要获取assets文件夹下的所有文件,可通过如下方法:

 

复制代码
try {
            String[] files = getAssets().list("");
            
             for(String f : files){
                System.out.println(f);
            }
        }  catch (Exception e) {
             //  TODO: handle exception
}
复制代码


至于其他的资源存储,详见以下文档,以下是开发文档中的内容:

Android Projects

Android projects are the projects that eventually get built into an .apk file that you install onto a device. They contain things such as application source code and resource files. Some are generated for you by default, while others should be created if required. The following directories and files comprise an Android project:

src/
Contains your stub Activity file, which is stored at  src/your/package/namespace/ActivityName.java. All other source code files (such as  .java or  .aidl files) go here as well.
bin
Output directory of the build. This is where you can find the final  .apk file and other compiled resources.
jni
Contains native code sources developed using the Android NDK. For more information, see the  Android NDK documentation.
gen/
Contains the Java files generated by ADT, such as your  R.java file and interfaces created from AIDL files.
assets/
This is empty. You can use it to store raw asset files. Files that you save here are compiled into an  .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the the  AssetManager. For example, this is a good location for textures and game data.
res/
Contains application resources, such as drawable files, layout files, and string values. See  Application Resources for more information.
anim/
For XML files that are compiled into animation objects. See the  Animation resource type.
color/
For XML files that describe colors. See the  Color Values resource type.
drawable/
For bitmap files (PNG, JPEG, or GIF), 9-Patch image files, and XML files that describe Drawable shapes or a Drawable objects that contain multiple states (normal, pressed, or focused). See the  Drawable resource type.
layout/
XML files that are compiled into screen layouts (or part of a screen). See the  Layout resource type.
menu/
For XML files that define application menus. See the  Menus resource type.
raw/
For arbitrary raw asset files. Saving asset files here instead of in the  assets/ directory only differs in the way that you access them. These files are processed by aapt and must be referenced from the application using a resource identifier in the  R class. For example, this is a good place for media, such as MP3 or Ogg files.
values/
For XML files that are compiled into many kinds of resource. Unlike other resources in the  res/ directory, resources written to XML files in this folder are not referenced by the file name. Instead, the XML element type controls how the resources is defined within them are placed into the  R class.
xml/
For miscellaneous XML files that configure application components. For example, an XML file that defines a  PreferenceScreenAppWidgetProviderInfo, or  Searchability Metadata. See  Application Resources for more information about configuring these application components.
libs/
Contains private libraries.
AndroidManifest.xml
The control file that describes the nature of the application and each of its components. For instance, it describes: certain qualities about the activities, services, intent receivers, and content providers; what permissions are requested; what external libraries are needed; what device features are required, what API Levels are supported or required; and others. See the  AndroidManifest.xml documentation for more information
project.properties
This file contains project settings, such as the build target. This file is integral to the project, so maintain it in a source revision control system. To edit project properties in Eclipse, right-click the project folder and select Properties.
local.properties
Customizable computer-specific properties for the build system. If you use Ant to build the project, this contains the path to the SDK installation. Because the content of the file is specific to the local installation of the SDK, the  local.properties should not be maintained in a source revision control system. If you use Eclipse, this file is not used.
ant.properties
Customizable properties for the build system. You can edit this file to override default build settings used by Ant and also provide the location of your keystore and key alias so that the build tools can sign your application when building in release mode. This file is integral to the project, so maintain it in a source revision control system. If you use Eclipse, this file is not used.
build.xml
The Ant build file for your project. This is only applicable for projects that you build with Ant.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值