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; android

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

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

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

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

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

 /**
  * 將文件轉換成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();
   }
  } utf-8

  return file;
 } ci

 /***
  * 建立文件
  *
  * @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();
    }

}

相關文章
相關標籤/搜索