写文件到sdcard

package com.**;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by hr on 2016/8/22.
 */
public class CopyFile2SDCard {
    private Context context;
//    private String srcFilePath;//源文件路径
//    private String targetFilePath;//目标路径
//    private String fileName;//文件名

    //String srcFilePath,String targetFilePath,String fileName
    public CopyFile2SDCard(Context context) {
        this.context = context;
//        this.srcFilePath= srcFilePath;
//        this.fileName= fileName;
//        this.targetFilePath = targetFilePath;
//        if(!isExits()){
//            writeFile2SDCard(srcFilePath,targetFilePath,fileName);
//        }
    }

    /**
     * 写文件到sdcard
     * @param srcFilePath 源文件路径
     * @param targetFilePath 目标文件路径
     * @param fileName 文件名
     */
    public void writeFile2SDCard(String srcFilePath,String targetFilePath,String fileName){
        InputStream in =null;
        try {
            in = new FileInputStream(srcFilePath);
            File file =new  File(targetFilePath);
            if(!file.exists()){
                file.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(targetFilePath+fileName);
            byte[] buffer =new byte[1024];
            int count=0;
            while ((count=in.read(buffer))>0){
                out.write(buffer,0,count);
            }
            out.flush();
            out.close();
            in.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 判断文件是否存在
     * @return
     */
    public boolean isExits(String targetFilePath,String fileName){
        File  file = new File(targetFilePath+fileName);
        if(file.exists()){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 讲一个字符串的内容写出到sdcard 进行保存
     * @param s
     * @param targetPath
     * @param fileName
     */
    public void writeString2SDCard(String s,String targetPath,String fileName){
        File file = new File(targetPath);
        if(!file.exists()){
            file.mkdirs();
        }
        try {
            FileOutputStream out = new FileOutputStream(targetPath+ fileName);
            out.write(s.getBytes(),0,s.length());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值