今天住的地方热哭我,吐槽完了。。。
准备工作
申请权限: 读取外部文件的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
一些方法:
getDir(String name ,int mode):获取应用程序的数据文件夹下获取或者创建name对应的子目录getFilesDir():数据文件夹的绝对路径String[] fileList():数据文件夹的全部文件deleteFile(String):删除指定文件
读取内部文件
新建一个内部文件:
File file =
new File(getFilesDir(),
"text.txt");
try {
boolean isSuccess = file.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
写文件:
try {
FileOutputStream files = openFileOutput(
"text2.txt" , Context
.MODE_PRIVATE)
files
.write(string
.getBytes())
files
.close()
} catch (IOException e) {
e
.printStackTrace()
}
还有输入流:FileInputStream openFileInput(String name)。
读写SD卡
先判断手机上是否插入了SD卡
String state =
Environment.getExternalStorageState();
if(TextUtils.equals(state,
Environment.MEDIA_MOUNTED))
{
//do some thing
}
获取外部存储器,就是sd卡的目录
File sd = Environment.getExternalStorageDirectory();
String filePath = Environment.getDownloadCacheDirectory().getAbsolutePath();
Environment.getDataDirectory();
Environment.getDownloadCacheDirectory();
然后就是各种读写操作
读取Assets
open后面必须是一个文件,不能是文件夹
void testAssets(){
WebView webview =
new WebView(
this);
webview.loadUrl(
"file:///android_asset/text.html");
try {
InputStream inputStream = getResources().getAssets().open(
"text.html");
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(FirstActivity.
this,
"文件读取错误", Toast.LENGTH_LONG);
}
读取列表
try {
String[] fileNames = getAssets().list(
"images");
}
catch (IOException e) {
e.printStackTrace();
}
读音乐文件
try {
AssetFileDescriptor a = getAssets()
.openFd(
"my.mp3")
MediaPlayer m = new MediaPlayer()
m
.setDataSource(
a
.getFileDescriptor(),
a
.getStartOffset(),
a
.getLength()
)
} catch (IOException e) {
e
.printStackTrace()
}
读图片
try {
InputStream inputStream = getAssets().open(
"imges/dpg.pg");
Bitmap imageView = BitmapFactory.decodeStream(inputStream);
}
catch (IOException e) {
e.printStackTrace();
}
res文件
InputStream input = getResource()
.openRawResouce(R
.raw.XXX)
这样 就可以访问
res和assets区别
相同点:原封不动的打包在apk里 不同点:
assets:什么都不动;res:会映射成一个int值
简单罗列,hehehe…
转载请注明原文地址: https://ju.6miu.com/read-1298199.html