Android开发中的文件操作工具类FileUtil完整实例

来源:爱站网时间:2020-05-07编辑:网友分享
Android开发和java开发有很多相似之处,其实在Java项目和Android项目中,文件存储是相同的,只是部分Android开发的路径被相应地处理过,有需要的朋友来爱站技术频道看看Android开发中的文件操作工具类FileUtil完整实例吧!

Android开发和java开发有很多相似之处,其实在Java项目和Android项目中,文件存储是相同的,只是部分Android开发的路径被相应地处理过,有需要的朋友来爱站技术频道看看Android开发中的文件操作工具类FileUtil完整实例吧!

package com.ymerp.android.tools;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.Reader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
/**
 * 文件操作工具
 *
 * @author chen.lin
 *
 */
public class FileUtil {
  private static final String TAG = "FileUtil";
  /**
   * 从sd卡取文件
   *
   * @param filename
   * @return
   */
  public String getFileFromSdcard(String filename) {
    ByteArrayOutputStream outputStream = null;
    FileInputStream fis = null;
    try {
      outputStream = new ByteArrayOutputStream();
      File file = new File(Environment.getExternalStorageDirectory(), filename);
      if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        fis = new FileInputStream(file);
        int len = 0;
        byte[] data = new byte[1024];
        while ((len = fis.read(data)) != -1) {
          outputStream.write(data, 0, len);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        outputStream.close();
        fis.close();
      } catch (IOException e) {
      }
    }
    return new String(outputStream.toByteArray());
  }
  /**
   * 保存文件到sd
   *
   * @param filename
   * @param content
   * @return
   */
  public static boolean saveContentToSdcard(String filename, String content) {
    boolean flag = false;
    FileOutputStream fos = null;
    try {
      File file = new File(Environment.getExternalStorageDirectory(), filename);
      if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        fos = new FileOutputStream(file);
        fos.write(content.getBytes());
        flag = true;
      }
    } catch (Exception e) {
      e.printStackTrace();
      flag = false;
    } finally {
      try {
        fos.close();
      } catch (IOException e) {
      }
    }
    return flag;
  }
  /**
   * 取得文件大小
   *
   * @param f
   * @return
   * @throws Exception
   */
  @SuppressWarnings("resource")
  public static long getFileSizes(File f) throws Exception {
    long size = 0;
    if (f.exists()) {
      FileInputStream fis = null;
      fis = new FileInputStream(f);
      size = fis.available();
    } else {
      f.createNewFile();
    }
    return size;
  }
  /**
   * 递归取得文件夹大小
   *
   * @param dir
   * @return
   * @throws Exception
   */
  public static long getFileSize(File dir) throws Exception {
    long size = 0;
    File flist[] = dir.listFiles();
    for (int i = 0; i = 0) {
        result += file.getPath() + "\n";
      }
    }
    if (result.equals("")) {
      result = "找不到文件!!";
    }
    return result;
  }
  /**
   * @detail 搜索sdcard文件
   * @param 需要进行文件搜索的目录
   * @param 过滤搜索文件类型
   * */
  public static List search(File file, String[] ext) {
    List list = new ArrayList();
    if (file != null) {
      if (file.isDirectory()) {
        File[] listFile = file.listFiles();
        if (listFile != null) {
          for (int i = 0; i  FindFile(File file, String keyword) {
    List list = new ArrayList();
    if (file.isDirectory()) {
      File[] files = file.listFiles();
      if (files != null) {
        for (File tempf : files) {
          if (tempf.isDirectory()) {
            if (tempf.getName().toLowerCase().lastIndexOf(keyword) > -1) {
              list.add(tempf);
            }
            list.addAll(FindFile(tempf, keyword));
          } else {
            if (tempf.getName().toLowerCase().lastIndexOf(keyword) > -1) {
              list.add(tempf);
            }
          }
        }
      }
    }
    return list;
  }
  /**
   * searchFile 查找文件并加入到ArrayList 当中去
   *
   * @param context
   * @param keyword
   * @param filepath
   * @return
   */
  public static List> searchFile(Context context, String keyword, File filepath) {
    List> list = new ArrayList>();
    Map rowItem = null;
    int index = 0;
    // 判断SD卡是否存在
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      File[] files = filepath.listFiles();
      if (files.length > 0) {
        for (File file : files) {
          if (file.isDirectory()) {
            if (file.getName().toLowerCase().lastIndexOf(keyword) > -1) {
              rowItem = new HashMap();
              rowItem.put("number", index); // 加入序列号
              rowItem.put("fileName", file.getName());// 加入名称
              rowItem.put("path", file.getPath()); // 加入路径
              rowItem.put("size", file.length() + ""); // 加入文件大小
              list.add(rowItem);
            }
            // 如果目录可读就执行(一定要加,不然会挂掉)
            if (file.canRead()) {
              list.addAll(searchFile(context, keyword, file)); // 如果是目录,递归查找
            }
          } else {
            // 判断是文件,则进行文件名判断
            try {
              if (file.getName().indexOf(keyword) > -1 || file.getName().indexOf(keyword.toUpperCase()) > -1) {
                rowItem = new HashMap();
                rowItem.put("number", index); // 加入序列号
                rowItem.put("fileName", file.getName());// 加入名称
                rowItem.put("path", file.getPath()); // 加入路径
                rowItem.put("size", file.length() + ""); // 加入文件大小
                list.add(rowItem);
                index++;
              }
            } catch (Exception e) {
              Toast.makeText(context, "查找发生错误!", Toast.LENGTH_SHORT).show();
            }
          }
        }
      }
    }
    return list;
  }
  /**
   * 根据后缀得到文件类型
   *
   * @param fileName
   * @param pointIndex
   * @return
   */
  public static String getFileType(String fileName, int pointIndex) {
    String type = fileName.substring(pointIndex + 1).toLowerCase();
    if ("m4a".equalsIgnoreCase(type) || "xmf".equalsIgnoreCase(type) || "ogg".equalsIgnoreCase(type) || "wav".equalsIgnoreCase(type)
        || "m4a".equalsIgnoreCase(type) || "aiff".equalsIgnoreCase(type) || "midi".equalsIgnoreCase(type)
        || "vqf".equalsIgnoreCase(type) || "aac".equalsIgnoreCase(type) || "flac".equalsIgnoreCase(type)
        || "tak".equalsIgnoreCase(type) || "wv".equalsIgnoreCase(type)) {
      type = "ic_file_audio";
    } else if ("mp3".equalsIgnoreCase(type) || "mid".equalsIgnoreCase(type)) {
      type = "ic_file_mp3";
    } else if ("avi".equalsIgnoreCase(type) || "mp4".equalsIgnoreCase(type) || "dvd".equalsIgnoreCase(type)
        || "mid".equalsIgnoreCase(type) || "mov".equalsIgnoreCase(type) || "mkv".equalsIgnoreCase(type)
        || "mp2v".equalsIgnoreCase(type) || "mpe".equalsIgnoreCase(type) || "mpeg".equalsIgnoreCase(type)
        || "mpg".equalsIgnoreCase(type) || "asx".equalsIgnoreCase(type) || "asf".equalsIgnoreCase(type)
        || "flv".equalsIgnoreCase(type) || "navi".equalsIgnoreCase(type) || "divx".equalsIgnoreCase(type)
        || "rm".equalsIgnoreCase(type) || "rmvb".equalsIgnoreCase(type) || "dat".equalsIgnoreCase(type)
        || "mpa".equalsIgnoreCase(type) || "vob".equalsIgnoreCase(type) || "3gp".equalsIgnoreCase(type)
        || "swf".equalsIgnoreCase(type) || "wmv".equalsIgnoreCase(type)) {
      type = "ic_file_video";
    } else if ("bmp".equalsIgnoreCase(type) || "pcx".equalsIgnoreCase(type) || "tiff".equalsIgnoreCase(type)
        || "gif".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type) || "tga".equalsIgnoreCase(type)
        || "exif".equalsIgnoreCase(type) || "fpx".equalsIgnoreCase(type) || "psd".equalsIgnoreCase(type)
        || "cdr".equalsIgnoreCase(type) || "raw".equalsIgnoreCase(type) || "eps".equalsIgnoreCase(type)
        || "gif".equalsIgnoreCase(type) || "jpg".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type)
        || "png".equalsIgnoreCase(type) || "hdri".equalsIgnoreCase(type) || "ai".equalsIgnoreCase(type)) {
      type = "ic_file_image";
    } else if ("ppt".equalsIgnoreCase(type) || "doc".equalsIgnoreCase(type) || "xls".equalsIgnoreCase(type)
        || "pps".equalsIgnoreCase(type) || "xlsx".equalsIgnoreCase(type) || "xlsm".equalsIgnoreCase(type)
        || "pptx".equalsIgnoreCase(type) || "pptm".equalsIgnoreCase(type) || "ppsx".equalsIgnoreCase(type)
        || "maw".equalsIgnoreCase(type) || "mdb".equalsIgnoreCase(type) || "pot".equalsIgnoreCase(type)
        || "msg".equalsIgnoreCase(type) || "oft".equalsIgnoreCase(type) || "xlw".equalsIgnoreCase(type)
        || "wps".equalsIgnoreCase(type) || "rtf".equalsIgnoreCase(type) || "ppsm".equalsIgnoreCase(type)
        || "potx".equalsIgnoreCase(type) || "potm".equalsIgnoreCase(type) || "ppam".equalsIgnoreCase(type)) {
      type = "ic_file_office";
    } else if ("txt".equalsIgnoreCase(type) || "text".equalsIgnoreCase(type) || "chm".equalsIgnoreCase(type)
        || "hlp".equalsIgnoreCase(type) || "pdf".equalsIgnoreCase(type) || "doc".equalsIgnoreCase(type)
        || "docx".equalsIgnoreCase(type) || "docm".equalsIgnoreCase(type) || "dotx".equalsIgnoreCase(type)) {
      type = "ic_file_text";
    } else if ("ini".equalsIgnoreCase(type) || "sys".equalsIgnoreCase(type) || "dll".equalsIgnoreCase(type)
        || "adt".equalsIgnoreCase(type)) {
      type = "ic_file_system";
    } else if ("rar".equalsIgnoreCase(type) || "zip".equalsIgnoreCase(type) || "arj".equalsIgnoreCase(type)
        || "gz".equalsIgnoreCase(type) || "z".equalsIgnoreCase(type) || "7Z".equalsIgnoreCase(type) || "GZ".equalsIgnoreCase(type)
        || "BZ".equalsIgnoreCase(type) || "ZPAQ".equalsIgnoreCase(type)) {
      type = "ic_file_rar";
    } else if ("html".equalsIgnoreCase(type) || "htm".equalsIgnoreCase(type) || "java".equalsIgnoreCase(type)
        || "php".equalsIgnoreCase(type) || "asp".equalsIgnoreCase(type) || "aspx".equalsIgnoreCase(type)
        || "jsp".equalsIgnoreCase(type) || "shtml".equalsIgnoreCase(type) || "xml".equalsIgnoreCase(type)) {
      type = "ic_file_web";
    } else if ("exe".equalsIgnoreCase(type) || "com".equalsIgnoreCase(type) || "bat".equalsIgnoreCase(type)
        || "iso".equalsIgnoreCase(type) || "msi".equalsIgnoreCase(type)) {
      type = "ic_file_exe";
    } else if ("apk".equalsIgnoreCase(type)) {
      type = "ic_file_apk";
    } else {
      type = "ic_file_normal";
    }
    return type;
  }
  /**
   * 改变文件大小显示的内容
   *
   * @param size
   * @return
   */
  public static String changeFileSize(String size) {
    if (Integer.parseInt(size) > 1024) {
      size = Integer.parseInt(size) / 1024 + "K";
    } else if (Integer.parseInt(size) > (1024 * 1024)) {
      size = Integer.parseInt(size) / (1024 * 1024) + "M";
    } else if (Integer.parseInt(size) > (1024 * 1024 * 1024)) {
      size = Integer.parseInt(size) / (1024 * 1024 * 1024) + "G";
    } else {
      size += "B";
    }
    return size;
  }
  /**
   * 得到所有文件
   *
   * @param dir
   * @return
   */
  public static ArrayList getAllFiles(File dir) {
    ArrayList allFiles = new ArrayList();
    // 递归取得目录下的所有文件及文件夹
    File[] files = dir.listFiles();
    for (int i = 0; i  readFile(File file, int startLine, int lineCount) {
    if (file == null || startLine  list = null;
    try {
      list = new ArrayList();
      fileReader = new FileReader(file);
      LineNumberReader lineReader = new LineNumberReader(fileReader);
      boolean end = false;
      for (int i = 1; i  100) {
      baos.reset();
      options -= 10;
      bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
    }
    try {
      FileOutputStream fos = new FileOutputStream(file);
      fos.write(baos.toByteArray());
      fos.flush();
      fos.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * 将图片从本地读到内存时,进行压缩 ,即图片从File形式变为Bitmap形式
   * 特点: 通过设置采样率, 减少图片的像素, 达到对内存中的Bitmap进行压缩
   * @param srcPath
   * @return
   */
  public static Bitmap compressImageFromFile(String srcPath, float pixWidth, float pixHeight) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;// 只读边,不读内容
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, options);
    options.inJustDecodeBounds = false;
    int w = options.outWidth;
    int h = options.outHeight;
    //float pixWidth = 800f;//
    //float pixHeight = 480f;//
    int scale = 1;
    if (w > h && w > pixWidth) {
      scale = (int) (options.outWidth / pixWidth);
    } else if (w  pixHeight) {
      scale = (int) (options.outHeight / pixHeight);
    }
    if (scale 

关于Android开发中的文件操作工具类FileUtil完整实例爱站技术频道就为大家介绍到这里了,可能还有很多朋友不了解这方面的知识的,所以关注js.aizhan.com推荐的文章一定会让你受益匪浅。 

上一篇:android实现不同对话框的方式

下一篇:Android开发实现ImageView加载摄像头拍摄的大图功能

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载