android 本地文件那点事

/**
 * 文件操作类整理
 *
 * @author zhiyuan 1.判断sd卡挂载且可用
 *
 *         2.判断sd卡有无文件名 3.删除已经存在的文件 4.将已存在的文件转换为bitmap 5.通过输入流写入文件 6.删除文件目录
 *         7.读取文件字符串 8.从流中读取文件 9.将文本内容写入文件 10.复制文件 11.递归创建文件目录 12.获取一个文件夹大小
 */
public class FileUtil {
 public String SDCARD = null;
 private static final int BUFFER = 8192;
 public static final long B = 1;
 public static final long KB = B * 1024;
 public static final long MB = KB * 1024;
 public static final long GB = MB * 1024;

 public FileUtil() {
  SDCARD = Environment.getExternalStorageDirectory() + "/";
 }

 /**
  * 获得sd卡路径
  *
  * @return
  */
 public static String sdcardPath() {
  return Environment.getExternalStorageDirectory() + "/";
 }

 /**
  * sd卡挂载且可用
  *
  * @return true/false
  */
 public static boolean isSdCardMounted() {
  return android.os.Environment.getExternalStorageState().equals(
    android.os.Environment.MEDIA_MOUNTED);
 }

 /**
  * 判断是否存才该文件名
  *
  * @param fileName
  * @return
  */
 public boolean existSDFile(String fileName) {
  File file = new File(SDCARD + fileName);
  return file.exists();
 }

 /**
  * 删除已有文件
  *
  * @param fileName
  */
 public void deleteExistFile(String fileName) {
  File file = new File(SDCARD + fileName);
  if (file.exists()) {
   file.delete();
  }
 }

 /**
  * 将文件转换成bitmap
  *
  * @param fileName
  * @return bitmap
  */
 public Bitmap loadSDBitmap(String fileName) {
  Bitmap btp = BitmapFactory.decodeFile(SDCARD + fileName);
  return btp;
 }

 /**
  * 从输入流写入到文件
  *
  * @param path
  * @param fileName
  *            文件名
  * @param is
  *            输入流
  * @return 文件
  */
 public File writeFileFromInputSteam(String path, String fileName,
   InputStream is) {
  File file = null;
  OutputStream os = null;
  try {
   file = createFile(SDCARD + path + fileName);
   os = new FileOutputStream(file);
   byte[] buffer = new byte[1024];
   int len;
   while ((len = is.read(buffer)) != -1) {
    os.write(buffer, 0, len);
    // os.write(buffer);
   }
   os.flush();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (os != null) {
     os.close();
    }
    is.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

  return file;
 }

 /***
  * 创建文件
  *
  * @param path
  * @return
  * @throws NullPointerException
  */
 public File createFile(String path) throws NullPointerException {
  File file = new File(path);
  File parent = new File(file.getAbsolutePath().substring(0,
    file.getAbsolutePath().lastIndexOf(File.separator)));
  if (!parent.exists()) {
   createFile(parent.getPath());
   parent.mkdirs();
  }
  return file;
 }

 /**
  * 格式化文件到MB
  *
  * @param paramLong
  * @return
  */
 public static String formatFileSizeForMb(long paramLong) {
  double tmp = paramLong;
  final double sign = 1024;
  String str = "";
  DecimalFormat dFormat = new DecimalFormat("0");
  tmp = paramLong / sign;
  // if (tmp >= sign) {
  tmp = tmp / sign;
  str = dFormat.format(tmp);
  // } else {
  // str = dFormat.format(tmp) + "KB";
  // }
  return str;
 }

 /**
  * 删除文件。
  *
  * @param file
  *            出入file路径
  * @return 删除成功返回true,失败返回false;
  */
 public static boolean deleteFile(File file) {
  File[] files = file.listFiles();
  if (files != null) {
   for (File deleteFile : files) {
    if (deleteFile.exists()) {
     if (deleteFile.isDirectory()) {
      // 如果是文件夹,则递归删除下面的文件后再删除该文件夹
      if (!deleteFile(deleteFile)) {
       // 如果失败则返回
       return false;
      }
     } else {
      if (!deleteFile.delete()) {
       // 如果失败则返回
       return false;
      }
     }
    }
   }
  }
  return file.delete();
 }

 /**
  * 读文件内容转换成字符串
  *
  * @param file
  * @return
  * @throws IOException
  */
 public static String readTextFile(File file) throws IOException {
  String text = null;
  InputStream is = null;
  try {
   is = new FileInputStream(file);
   text = readTextInputStream(is);
  } finally {
   if (is != null) {
    is.close();
   }
  }
  return text;
 }

 /**
  * 将输入流转换成字符串
  *
  * @param is
  * @return
  * @throws IOException
  */
 public static String readTextInputStream(InputStream is) throws IOException {
  StringBuffer strbuffer = new StringBuffer();
  String line;
  BufferedReader reader = null;
  try {
   reader = new BufferedReader(new InputStreamReader(is));
   while ((line = reader.readLine()) != null) {
    strbuffer.append(line).append("\r\n");
   }
  } finally {
   if (reader != null) {
    reader.close();
   }
  }
  return strbuffer.toString();
 }

 /**
  * 将文本内容写入文件
  *
  * @param file
  * @param str
  * @throws IOException
  */
 public static void writeTextFile(File file, String str) throws IOException {
  DataOutputStream out = null;
  try {
   out = new DataOutputStream(new FileOutputStream(file));
   out.write(str.getBytes());
  } finally {
   if (out != null) {
    out.close();
   }
  }
 }

 /**
  * 复制文件
  *
  * @param sourceFile
  * @param targetFile
  * @throws IOException
  */
 public static void copyFile(File sourceFile, File targetFile)
   throws IOException {
  BufferedInputStream inBuff = null;
  BufferedOutputStream outBuff = null;
  try {
   inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
   outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
   byte[] buffer = new byte[BUFFER];
   int length;
   while ((length = inBuff.read(buffer)) != -1) {
    outBuff.write(buffer, 0, length);
   }
   outBuff.flush();
  } finally {
   if (inBuff != null) {
    inBuff.close();
   }
   if (outBuff != null) {
    outBuff.close();
   }
  }
 }

 /**
  * 格式化文件大小<b> 带有单位
  *
  * @param size
  * @return
  */
 public static double getSize(long size, long u) {
  return (double) size / (double) u;
 }

 /**
  * 保留两位小数
  *
  * @param d
  * @return
  */
 public static String twodot(double d) {
  return String.format("%.2f", d);
 }

 /**
  * 格式化文件大小<b> 带有单位
  *
  * @param size
  * @return
  */
 public static String formatFileSize(long size) {
  StringBuilder sb = new StringBuilder();
  String u = null;
  double tmpSize = 0;
  if (size < KB) {
   sb.append(size).append("B");
   return sb.toString();
  } else if (size < MB) {
   tmpSize = getSize(size, KB);
   u = "KB";
  } else if (size < GB) {
   tmpSize = getSize(size, MB);
   u = "MB";
  } else {
   tmpSize = getSize(size, GB);
   u = "GB";
  }
  return sb.append(twodot(tmpSize)).append(u).toString();
 }

 /**
  * 递归创建文件目录
  *
  * @param path
  */
 public static void CreateDir(String path) {
  if (!isSdCardMounted())
   return;
  File file = new File(path);
  if (!file.exists()) {
   try {
    file.mkdirs();
   } catch (Exception e) {
    Log.e("hulutan", "error on creat dirs:" + e.getStackTrace());
   }
  }
 }

 /**
  * 读取表情配置文件
  *
  * @param context
  * @return
  */
 public static List<String> getEmojiFile(Context context) {
  try {
   List<String> list = new ArrayList<String>();
   InputStream in = context.getResources().getAssets().open("emoji");// 文件名字为rose.txt
   BufferedReader br = new BufferedReader(new InputStreamReader(in,
     "UTF-8"));
   String str = null;
   while ((str = br.readLine()) != null) {
    list.add(str);
   }

   return list;
  } catch (IOException e) {
   e.printStackTrace();
  }
  return null;
 }

 /**
  * 获取一个文件夹大小
  *
  * @param f
  * @return
  * @throws Exception
  */
 public static long getFileSize(File f) {
  long size = 0;
  File flist[] = f.listFiles();
  for (int i = 0; i < flist.length; i++) {
   if (flist[i].isDirectory()) {
    size = size + getFileSize(flist[i]);
   } else {
    size = size + flist[i].length();
   }
  }
  return size;
 }

  /**
     *
     * @param mActivity
     * @param filePath
     * @return
     */
    public static String getString(Context context, int filePath) {
        Resources res = context.getResources();
        InputStream in = null;
        InputStreamReader inputStreamReader = null;
        try {
            in = res.openRawResource(filePath);
            inputStreamReader = new InputStreamReader(in, "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}

你可能感兴趣的:(文件,输入流.sd卡)