一. 前言
读取工程目录下的文件,包括 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
|
public void assetTest(){ WebView webView = findViewById(R.id.web_view); webView.loadUrl("file:///android_asset/html/test.html");
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(); }
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(); }
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(); }
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
|
public void resTest(){ Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher_background); XmlResourceParser layout = getResources().getLayout(R.layout.activity_main); InputStream is = getResources().openRawResource(R.raw.test); int color = getResources().getColor(R.color.colorAccent); String string = getResources().getString(R.string.app_name); }
|
四. 源代码
Github地址-other_storage模块