android 文件操作


package com.yangwei.Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.content.Context;
import android.os.Environment;

public class FileService {
   
    private Context context;
   
    public FileService(Context context) {
        super();
        this.context = context;
    }

    /**
     * 保存文件到系统存储中
     * @param title 文件名
     * @param content 文件内容
     * @param model 文件存储模式
     *  context.MODE_APPEND;------------私有追加模式
        context.MODE_PRIVATE;-----------私有覆蓋模式
        context.MODE_WORLD_READABLE;----外部可讀
        context.MODE_WORLD_WRITEABLE;---外部可写
     * @throws Exception
     */
   
    public void save(String title,String content,Integer mode) throws Exception{
       
        FileOutputStream fileOutputStream = context.openFileOutput(title, mode);
        fileOutputStream.write(content.getBytes());
        fileOutputStream.close();
       
    }
   
    /**
     * 读取项目内部指定文件
     * @param title
     * @return
     * @throws Exception
     */
   
    public String read(String title) throws Exception{
       
        FileInputStream fileInputStream = context.openFileInput(title);
        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while((len = fileInputStream.read(bytes)) != -1){
            arrayOutputStream.write(bytes, 0, len);
        }
        byte[] data = arrayOutputStream.toByteArray();
        return new String(data);
    }
   
    /**
     * 保存到sdcard上
     * Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)判断是否可用SD卡
     * @param title
     * @param content
     * @throws Exception
     */
    public void saveToSD(String title,String content) throws Exception{
       
        File file = new File(Environment.getExternalStorageDirectory(), title);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(content.getBytes());
        fileOutputStream.close();       
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值