android文件操作常用方法

判断文件是否存在:

/**
     * 判断文件是否存在。
     * @param filePath 文件路径。
     * @return 文件是否存在。
     */
public satic boolean hostIsExistFIle(String filePath){
    File file = new File(filePath);
    if(file.exists()){
        return true;
    }
    return false;
}

SD卡写入文件操作:

/**
     * <p>
     * 判断SDCard是否存在。
     * </p>
     * 
     * @return SD卡存在与否。
     */
public boolean isSDcardExists(){
    return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
/**
     * <p>
     * 获取SDCard路径。
     * </p>
     * 
     * @return SD卡路径。
     */
public static final String getSDcardRoot(){
    String root="";
    if(isSDcardExists()){
            root=Environment.getExternalStorageDirectory().toString()+"/";
    }
    return root;
}
/**
     * SD卡写入文件
     * @param content   文件内容
     * @param fileName  文件名字(包含SD卡路径)
     * @return
     */
public boolean writeFile(String content,String fileName){
    if(fileName.startWith(getSDcardRoot())){
        File file=null;
        FileOutPutStream fstream;
        try{
            file=new File(fileName);
            if(!file.exit()){
                File fileDir=file.getParentFile();
                fileDir.mkdir();
            }
            file.createNewFile();
            fstream=new FileOutPutStream(file);
            byt[] buf=content.getByte();
            fstream.writ(buf);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(fstream!=null){
                try{
                    fstream.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }

        }
        return true;

    }else{
        Log.i("stats","文件只能写在SD卡中!");
    }
}

读取assets文件夹中的文件内容(String):

/**
     * 读取assets文件夹中的文件内容。
     * 
     * @param fileName
     *            文件名,含路径。
     * @return 文件内容字符串。
     */
public static String readAssetsFile(String fileName){
    String content;
    InputStream in;
    try{
        in=Context.getAssets().open(fileName);
        int length=in.available();
        byte[] buffer=new byte[length];
        in.read(buffer);
        content=new String(buffer,"UTF-8");
    }catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }       
    return content == null ? "" : content;
}
/**
     * <p>
     * 复制文件
     * </p>
     * 
     * @param in 输入流
     * @param targetPath 目标路径(文件路径)
     * 
     * @throws IOException 抛出异常
     */
    public static final void copyFile(InputStream in, String targetPath) throws IOException {
        if (in == null || Utils.isEmpty(targetPath)) {
            return;
        }

        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;

        try {
            File targetFile = new File(targetPath);
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }

            inBuff = new BufferedInputStream(in);
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile, false));

            // 缓冲数组
            byte[] bytes = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(bytes)) != -1) {
                outBuff.write(bytes, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        } finally {
            if (inBuff != null) {
                inBuff.close();
            }
            if (outBuff != null) {
                outBuff.close();
            }
        }
    }

    /**
     * <p>
     * 删除文件或目录。
     * </p>
     * 
     * @param filePath 文件路径
     * 
     * @return 删除成功返回true,否则返回false。
     */
    public static final boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            return file.delete();
        } else if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                for (File tempF : files) {
                    deleteFile(tempF.getPath());
                }
            }
            // 删除file 本身
            return file.delete();
        }
        return true;
    }

/**
     * 
     * 根据文件后缀名返回文件类型。
     * 
     * 
     * @param fileName 目标文件
     * 
     * @return 文件类型字符串。
     */
    public static final String getMIMEType(File fileName) {
        String type = "";
        String fName = fileName.getName();
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) {
            type = "image";
        } else if (end.equals("apk")) {
            type = "application/vnd.android.package-archive";
        } else if (end.equals("zip")) {
            type = "zip";
        } else if (end.equals("pdf")) {
            type = "pdf";
        } else if (end.equals("doc") || end.equals("docx")) {
            type = "doc";
        } else if (end.equals("xls") || end.equals("xlsx")) {
            type = "xls";
        } else if (end.equals("ppt") || end.equals("pptx")) {
            type = "ppt";
        } else if (end.equals("apk")) {

        } else {
            type += "/*";
        }
        return type;
    }

/**
     * <p>
     * 读取assets目录下文件。
     * </p>
     * 
     * @param context Context对象
     * @param filePath 文件目录
     * 
     * @return 文件内容,String型
     */
    public static final String readAssetFileToStr(Context context, String filePath) throws IOException {
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            inputStream = context.getAssets().open(filePath);
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            StringBuilder buffer = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line).append('\n');
            }
            return buffer.toString();
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值