一. 前言

读取工程目录下的文件,包括 assets目录下的文件、res目录下的文件。

二. 操作assets目录下的文件

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
/**
* 操作asset目录文件
*/
public void assetTest(){
//1.直接加载
WebView webView = findViewById(R.id.web_view);
webView.loadUrl("file:///android_asset/html/test.html");

//2.open的方式
try {
InputStream is = getResources().getAssets().open("html/test.html");
Toast.makeText(this, "文件读取成功", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "文件读取异常", Toast.LENGTH_SHORT).show();
}

//3.读取图片
try {
InputStream is = getResources().getAssets().open("img/test.png");
Toast.makeText(this, "图片读取成功", Toast.LENGTH_SHORT).show();

Bitmap bitmap = BitmapFactory.decodeStream(is);
ImageView imageView = findViewById(R.id.img);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "图片读取失败", Toast.LENGTH_SHORT).show();
}

//4.读取音乐
try {
AssetFileDescriptor afd = getAssets().openFd("music/test.mp3");
Toast.makeText(this, "音乐读取成功", Toast.LENGTH_SHORT).show();

MediaPlayer player = new MediaPlayer();
player.reset();
player.setDataSource(
afd.getFileDescriptor(),
afd.getStartOffset(),
afd.getLength()
);
player.prepare();
player.start();

} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "音乐读取失败", Toast.LENGTH_SHORT).show();
}

//5.读列表
try {
String[] list = getResources().getAssets().list("html");
for (String s : list) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}

三. 操作res目录下的文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 操作res目录文件
*/
public void resTest(){
//drawable
Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher_background);
//layout
XmlResourceParser layout = getResources().getLayout(R.layout.activity_main);
//raw
InputStream is = getResources().openRawResource(R.raw.test);
//values
int color = getResources().getColor(R.color.colorAccent);
String string = getResources().getString(R.string.app_name);
}

四. 源代码

Github地址-other_storage模块