在建立项目中一般会默认建立assets文件,当然我们还可以在res文件下面建立raw文件夹,这里面都可以存放一些图片,音频或者文本信息,可以供我们在程序当中进行使用,不过他们两个也有不同点。
assets下面的文件不会被编译,通过路径可以去访问其中的内容。raw中文件会自动编译,我们可以在R.java文件中找到对应的ID。
看下面截图:
那么既然这样那我们平时该怎么样进行把资源放入这两个文件当中呢?
我个人平时喜欢比较文件的大小,如果文件比较大一点的会放入到aeests文件中,因为用这个文件文件当中的信息,相当于要去进行IO流操作,比较耗时的操作
其中比较重要的是获取到Assets和Raw文件夹中的资源方法:
Assets: AssetManager assetManager = getAssets();
Raw: InputStream inputStream = getResources().openRawResource(R.raw.demo);
下面该Demo的Activity源代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
package com.jiangqq.aeesrtandraw; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.content.res.AssetManager; import android.os.Bundle; import android.widget.EditText; /** * * * * */ public class AeesrtsAndRawActivity extends Activity private EditText @Override public void onCreate(Bundle super .onCreate(savedInstanceState); setContentView(R.layout.main); readAssets(); readRaw(); } /** * */ private void readAssets() et1 AssetManager try { InputStream "demo.txt" ); et1.setText(read(inputStream)); } catch (IOException e.printStackTrace(); } } /** * */ private void readRaw() et2 InputStream et2.setText(read(inputStream)); } /** * * * * */ private String try { ByteArrayOutputStream new ByteArrayOutputStream(); int length; while ((length 1 ) oStream.write(length); } return oStream.toString(); } catch (IOException return "文件读写失败" ; } } } |
布局文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
<? xml version = "1.0" encoding = "utf-8" ?> android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:orientation = "vertical" > < LinearLayout android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:orientation = "horizontal" > < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "@string/et1" /> < EditText android:id = "@+id/et1" android:layout_width = "fill_parent" android:layout_height = "wrap_content" /> </ LinearLayout > < LinearLayout android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:orientation = "horizontal" > < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "@string/et2" /> < EditText android:id = "@+id/et2" android:layout_width = "fill_parent" android:layout_height = "wrap_content" /> </ LinearLayout > </ LinearLayout > |
Demo运行效果截图: