android中文件操作
发布时间:2020-05-24 18:39:21 所属栏目:Java 来源:互联网
导读:android中文件操作
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 android开发中涉及到的文件操作主要是往sd卡中或是内在中读取文件数据,大概的操作如下:public class FileOperator {
private Context context; //上下文
public FileOperator(Context c) {
this.context = c;
}
//首先是个公用的方法:
private String dealStream(InputStream is) throws IOException {
int buffersize = is.available();// 取得输入流的字节长度
byte buffer[] = new byte[buffersize];
is.read(buffer);// 数据读入数组
is.close();// 读取完毕关闭流。
String result = EncodingUtils.getString(buffer,"UTF-8");// 防止乱码
return result;
}
// 读取sd中的存在的文件
public String readSDCardFile(String path) throws IOException {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
String resStr = dealStream(fis);
return resStr ;
}
// res目录下新建raw资源文件夹,只能读不能写入
public String readRawFile(int fileId) throws IOException {
// 取得输入流
InputStream is = context.getResources().openRawResource(fileId);
String resultStr = dealStream(is);// 返回一个字符串
return resultStr;
}
// 在assets下的文件,只能读取不能写入
public String readAssetsFile(String filename) throws IOException {
// 取得输入流
InputStream is = context.getResources().getAssets().open(filename);
String resStr = dealStream(is);// 返回一个字符串
return resStr;
}
// 往sd卡中写入文件
public void writeToSDCard(String path,byte[] buffer) throws IOException {
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file);
fos.write(buffer);// 写入buffer数组。如果想写入一些简单的字符,可以将String.getBytes()再写入文件;
fos.close();
}
// 将文件写入应用的data/data的files目录下
public void writeToDateFile(String fileName,byte[] buffer) throws Exception {
byte[] buf = fileName.getBytes("iso8859-1");
fileName = new String(buf,"utf-8");
FileOutputStream fos = context.openFileOutput(fileName,Context.MODE_APPEND);// 打开模式,有几种,此处表示添加在文件后面
fos.write(buffer);
fos.close();
}
// 读取应用的data/data的files目录下文件数据
public String readDateFile(String fileName) throws Exception {
FileInputStream fis = context.openFileInput(fileName);
String resultStr = dealStream(fis);// 返回一个字符串
return resultStr;
}
}
最后我们不要忘记在清单文件AndroidManfiest.xml中加上sd卡操作权限: <uses-permissionandroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>//在SDCard中创建与删除文件权限 <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/> //往SDCard写入数据权限 以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
