android中文件操作

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-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> //在SDCard中创建与删除文件权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />   //往SDCard写入数据权限

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值