file,bitmap工具类

10 篇文章 0 订阅

发几个工具类,bitmap,file的

package com.angelonline.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;

import com.angelonline.activity.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class BitmapUtil {

//	public static void setPicToImageView(ImageView imageView, File imageFile) {
//		
//		if (!imageFile.exists()) {
//			try {
//				File tempf = new File(imageFile.getParent(),
//						FileUtil.UNHANDLE_PHOTO + ".jpg");
//				Bitmap bmp = BitmapFactory.decodeFile(tempf.getAbsolutePath());
//				bmp.compress(Bitmap.CompressFormat.JPEG, 100,
//						new FileOutputStream(imageFile));
//			} catch (Exception e) {
//				return;
//			}
//		}
//
//		int imageViewWidth = imageView.getWidth();
//		int imageViewHeight = imageView.getHeight();
//		BitmapFactory.Options opts = new Options();
//
//		// 设置这个,只得到Bitmap的属性信息放入opts,而不把Bitmap加载到内存中
//		opts.inJustDecodeBounds = true;
//		BitmapFactory.decodeFile(imageFile.getPath(), opts);
//
//		int bitmapWidth = opts.outWidth;
//		int bitmapHeight = opts.outHeight;
//		// 取最大的比例,保证整个图片的长或者宽必定在该屏幕中可以显示得下
//		int scale = Math.max(imageViewWidth / bitmapWidth, imageViewHeight
//				/ bitmapHeight);
//
//		// 缩放的比例
//		opts.inSampleSize = scale;
//		// 内存不足时可被回收
//		opts.inPurgeable = true;
//		// 设置为false,表示不仅Bitmap的属性,也要加载bitmap
//		opts.inJustDecodeBounds = false;
//
//		Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath(), opts);
//		
//		imageView.setImageBitmap(comp(bitmap));
//	}

	public static Bitmap getSmallBitmap(ImageView imageView, File imageFile) {
		int imageViewWidth = imageView.getWidth();
		int imageViewHeight = imageView.getHeight();
		BitmapFactory.Options opts = new Options();

		// 设置这个,只得到Bitmap的属性信息放入opts,而不把Bitmap加载到内存中
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(imageFile.getPath(), opts);

		int bitmapWidth = opts.outWidth;
		int bitmapHeight = opts.outHeight;
		// 取最大的比例,保证整个图片的长或者宽必定在该屏幕中可以显示得下
		int scale = Math.max(imageViewWidth / bitmapWidth, imageViewHeight
				/ bitmapHeight);

		// 缩放的比例
		opts.inSampleSize = scale;
		// 内存不足时可被回收
		opts.inPurgeable = true;
		// 设置为false,表示不仅Bitmap的属性,也要加载bitmap
		opts.inJustDecodeBounds = false;

		return BitmapFactory.decodeFile(imageFile.getPath(), opts);
		// imageView.setImageBitmap(bitmap);
	}
	
	public static void setSmallBitmap(ImageView imageView, File imageFile) {
		int imageViewWidth = imageView.getWidth();
		int imageViewHeight = imageView.getHeight();
		BitmapFactory.Options opts = new Options();

		// 设置这个,只得到Bitmap的属性信息放入opts,而不把Bitmap加载到内存中
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(imageFile.getPath(), opts);

		int bitmapWidth = opts.outWidth;
		int bitmapHeight = opts.outHeight;
		// 取最大的比例,保证整个图片的长或者宽必定在该屏幕中可以显示得下
		int scale = Math.max(imageViewWidth / bitmapWidth, imageViewHeight
				/ bitmapHeight);

		// 缩放的比例
		opts.inSampleSize = scale;
		// 内存不足时可被回收
		opts.inPurgeable = true;
		// 设置为false,表示不仅Bitmap的属性,也要加载bitmap
		opts.inJustDecodeBounds = false;

		imageView.setImageBitmap(BitmapFactory.decodeFile(imageFile.getPath(), opts));
	}
	

	/**
	 * 读取本地资源的图片
	 * 
	 * @param context
	 * @param resId
	 * @return
	 */
	public static Bitmap ReadBitmapById(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}

	/***
	 * 根据资源文件获取Bitmap
	 * 
	 * @param context
	 * @param drawableId
	 * @return
	 */
	public static Bitmap ReadBitmapById(Context context, int drawableId,
			int screenWidth, int screenHight) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = Config.ARGB_8888;
		options.inInputShareable = true;
		options.inPurgeable = true;
		InputStream stream = context.getResources().openRawResource(drawableId);
		Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
		return getBitmap(bitmap, screenWidth, screenHight);
	}

	public static Bitmap ReadBitmapById(Context context, File imgFile,
			ImageView imgView, int screenWidth, int screenHight) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = Config.ARGB_8888;
		options.inInputShareable = true;
		options.inPurgeable = true;
		// InputStream stream =
		// context.getResources().openRawResource(drawableId);
		// Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
		Bitmap bitmap = getSmallBitmap(imgView, imgFile);
		return getBitmap(bitmap, screenWidth, screenHight);
	}

	/***
	 * 等比例压缩图片
	 * 
	 * @param bitmap
	 * @param screenWidth
	 * @param screenHight
	 * @return
	 */
	public static Bitmap getBitmap(Bitmap bitmap, int screenWidth,
			int screenHight) {
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();
		Log.e("jj", "图片宽度" + w + ",screenWidth=" + screenWidth);
		Matrix matrix = new Matrix();
		float scale = (float) screenWidth / w;
		float scale2 = (float) screenHight / h;

		// scale = scale < scale2 ? scale : scale2;

		// 保证图片不变形.
		matrix.postScale(scale, scale);
		// w,h是原图的属性.
		return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
	}

	private static int FREE_SD_SPACE_NEEDED_TO_CACHE = 1;
	private static int MB = 1024 * 1024;
	public final static String DIR = "/sdcard/hypers";

	/***
	 * 保存图片至SD卡
	 * 
	 * @param bm
	 * @param url
	 * @param quantity
	 */
	public static void saveBmpToSd(Bitmap bm, String fileName, int quantity) {
		// 判断sdcard上的空间
		if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
			return;
		}
		if (!Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState()))
			return;
		String filename = fileName;
		// 目录不存在就创建
		File dirPath = new File(DIR);
		if (!dirPath.exists()) {
			dirPath.mkdirs();
		}

		File file = new File(DIR + "/" + filename + ".jpg");
		try {
			file.createNewFile();
			OutputStream outStream = new FileOutputStream(file);
			bm.compress(Bitmap.CompressFormat.JPEG, quantity, outStream);
			outStream.flush();
			outStream.close();

		} catch (FileNotFoundException e) {

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void saveBmpToSd(Bitmap bm, String path, String fileName,
			int quantity) {
		// 判断sdcard上的空间
		if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
			return;
		}
		if (!Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState()))
			return;
		String filename = fileName;
		// 目录不存在就创建
		File dirPath = new File(path);
		if (!dirPath.exists()) {
			dirPath.mkdirs();
		}

		File file = new File(path + "/" + filename + ".jpg");
		try {
			file.createNewFile();
			OutputStream outStream = new FileOutputStream(file);
			bm.compress(Bitmap.CompressFormat.JPEG, quantity, outStream);
			outStream.flush();
			outStream.close();

		} catch (FileNotFoundException e) {

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/***
	 * 获取SD卡图片
	 * 
	 * @param url
	 * @param quantity
	 * @return
	 */
	public static Bitmap GetBitmap(String url, int quantity) {
		InputStream inputStream = null;
		String filename = "";
		Bitmap map = null;
		URL url_Image = null;
		String LOCALURL = "";
		if (url == null)
			return null;
		try {
			filename = url;
		} catch (Exception err) {
		}

		LOCALURL = URLEncoder.encode(filename);
		if (Exist(DIR + "/" + LOCALURL)) {
			map = BitmapFactory.decodeFile(DIR + "/" + LOCALURL);
		} else {
			try {
				url_Image = new URL(url);
				inputStream = url_Image.openStream();
				map = BitmapFactory.decodeStream(inputStream);
				// url = URLEncoder.encode(url, "UTF-8");
				if (map != null) {
					saveBmpToSd(map, LOCALURL, quantity);
				}
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		return map;
	}

	/***
	 * 判断图片是存在
	 * 
	 * @param url
	 * @return
	 */
	public static boolean Exist(String url) {
		File file = new File(DIR + url);
		return file.exists();
	}

	/** * 计算sdcard上的剩余空间 * @return */
	private static int freeSpaceOnSd() {
		StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
				.getPath());
		double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
				.getBlockSize()) / MB;

		return (int) sdFreeMB;
	}

	public static Bitmap convertViewToBitmap(View view, int bitmapWidth,
			int bitmapHeight) {
		Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
				Bitmap.Config.ARGB_8888);
		view.draw(new Canvas(bitmap));

		return bitmap;
	}

	private static DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
			.cacheInMemory(true).cacheOnDisk(true)
			// .showImageOnLoading(R.drawable.btn_refresh)
			.showImageForEmptyUri(R.drawable.un_load)
			.showImageOnFail(R.drawable.un_load)
			// .displayer(new FadeInBitmapDisplayer(100))
			.bitmapConfig(Bitmap.Config.RGB_565).build();

	/**
	 * options 为null 时,使用默认值(建议使用默认options)
	 * 
	 * @param uri
	 * @param imageView
	 * @param options
	 */
	public static void disaplayImage(String uri, ImageView imageView,
			DisplayImageOptions options) {
		DisplayImageOptions ops = defaultOptions;
		if (options != null) {
			ops = options;
		}
		ImageLoader.getInstance().displayImage(uri, imageView, ops);

	}

	public static void disaplayImage(File file, ImageView imageView,
			DisplayImageOptions options) {
		String uri = Uri.fromFile(file).toString();
		disaplayImage(uri, imageView, options);
	}

	public static void writeSmallToSD(int size, Bitmap image) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 85, out);
		float zoom = (float) Math.sqrt(size * 1024
				/ (float) out.toByteArray().length);

		Matrix matrix = new Matrix();
		matrix.setScale(zoom, zoom);

		Bitmap result = Bitmap.createBitmap(image, 0, 0, image.getWidth(),
				image.getHeight(), matrix, true);

		out.reset();
		result.compress(Bitmap.CompressFormat.JPEG, 85, out);
		while (out.toByteArray().length > size * 1024) {
			System.out.println(out.toByteArray().length);
			matrix.setScale(0.9f, 0.9f);
			result = Bitmap.createBitmap(result, 0, 0, result.getWidth(),
					result.getHeight(), matrix, true);
			out.reset();
			result.compress(Bitmap.CompressFormat.JPEG, 85, out);
		}
	}

	public static String getCameraTempDir() {
		File tempf = new File(DIR);
		if (!tempf.exists())
			tempf.mkdirs();
		return tempf.getAbsolutePath();
	}

	public static Bitmap compressImageFromFile(String srcPath, float width,
			float height) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		newOpts.inJustDecodeBounds = true;// 只读边,不读内容
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		float hh = width;//
		float ww = height;//
		int be = 1;
		if (w > h && w > ww) {
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置采样率

		newOpts.inPreferredConfig = Config.ARGB_8888;// 该模式是默认的,可不设
		newOpts.inPurgeable = true;// 同时设置才会有效
		newOpts.inInputShareable = true;// 。当系统内存不够时候图片自动被回收

		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		// return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
		// 其实是无效的,大家尽管尝试
		return bitmap;
	}

	public static Bitmap compressImageFromFile(String srcPath) {
		return compressImageFromFile(srcPath, 80f, 80f);
	}

	public static Bitmap compressImageFromFile(String srcPath, String fileName) {
		Bitmap bmp = compressImageFromFile(srcPath);
		saveBmpToSd(bmp, fileName, 100);
		return bmp;
	}

	// int imageViewWidth = imageView.getWidth();
	// int imageViewHeight = imageView.getHeight();
	// BitmapFactory.Options opts = new Options();
	//
	// // 设置这个,只得到Bitmap的属性信息放入opts,而不把Bitmap加载到内存中
	// opts.inJustDecodeBounds = true;
	// BitmapFactory.decodeFile(imageFile.getPath(), opts);
	//
	// int bitmapWidth = opts.outWidth;
	// int bitmapHeight = opts.outHeight;
	// // 取最大的比例,保证整个图片的长或者宽必定在该屏幕中可以显示得下
	// int scale = Math.max(imageViewWidth / bitmapWidth, imageViewHeight
	// / bitmapHeight);
	//
	// // 缩放的比例
	// opts.inSampleSize = scale;
	// // 内存不足时可被回收
	// opts.inPurgeable = true;
	// // 设置为false,表示不仅Bitmap的属性,也要加载bitmap
	// opts.inJustDecodeBounds = false;
	//
	// return BitmapFactory.decodeFile(imageFile.getPath(), opts);

	/**
	 * 给bitmap加标签
	 * 
	 * @param src
	 * @param watermark
	 * @return
	 */
	public static Bitmap addWatermark(ImageView bgImage, Bitmap watermark) {
		bgImage.setDrawingCacheEnabled(true);
		Bitmap src = ((BitmapDrawable) bgImage.getDrawable()).getBitmap();
		if (src == null || watermark == null) {
			Log.d("texts", "src is null");
			return src;
		}

		Integer sWid = src.getWidth();
		Integer sHei = src.getHeight();
		Integer wWid = watermark.getWidth();
		Integer wHei = watermark.getHeight();
		if (sWid == 0 || sHei == 0) {
			return null;
		}

		if (sWid < wWid || sHei < wHei) {
			return src;
		}
		Integer currWid = bgImage.getWidth();
		float imgScale = sWid.floatValue() / currWid.floatValue();
		float markerWid = wWid.floatValue() * imgScale;
		float markerHei = wHei.floatValue() * imgScale;
		Bitmap currMark = BmpUtils.zoomBitmap(watermark, (int) markerWid,
				(int) markerHei);
		Bitmap bitmap = Bitmap.createBitmap(sWid, sHei, Config.RGB_565);
		try {
			Canvas cv = new Canvas(bitmap);
			cv.drawBitmap(src, 0, 0, null);
			cv.drawBitmap(currMark, 10, 10, null);
			cv.save(Canvas.ALL_SAVE_FLAG);
			cv.restore();
		} catch (Exception e) {
			bitmap = null;
			e.getStackTrace();
		}
		bgImage.setDrawingCacheEnabled(false);
		return bitmap;
	}

	
    public static Bitmap comp(Bitmap image) {  
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();         
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
        if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出    
            baos.reset();//重置baos即清空baos  
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%,把压缩后的数据存放到baos中  
        }  
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());  
        BitmapFactory.Options newOpts = new BitmapFactory.Options();  
        //开始读入图片,此时把options.inJustDecodeBounds 设回true了  
        newOpts.inJustDecodeBounds = true;  
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
        newOpts.inJustDecodeBounds = false;  
        int w = newOpts.outWidth;  
        int h = newOpts.outHeight;  
        //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为  
        float hh = 800f;//这里设置高度为800f  
        float ww = 480f;//这里设置宽度为480f  
        //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可  
        int be = 1;//be=1表示不缩放  
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
            be = (int) (newOpts.outWidth / ww);  
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放  
            be = (int) (newOpts.outHeight / hh);  
        }  
        if (be <= 0)  
            be = 1;  
        newOpts.inSampleSize = be;//设置缩放比例  
        //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了  
        isBm = new ByteArrayInputStream(baos.toByteArray());  
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩  
    }  
    
    public static Bitmap compressImage(Bitmap image) {  
    	  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中  
        int options = 100;  
        while ( baos.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩         
            baos.reset();//重置baos即清空baos  
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中  
            options -= 10;//每次都减少10  
        }  
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中  
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片  
        return bitmap;  
    }
	
}

package com.angelonline.utils;

	import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
	 
	/**
	 * 图片操作工具包
	 * 
	 * @author liux (http://my.oschina.net/liux)
	 * @version 1.0
	 * @created 2012-3-21
	 */
	public class BmpUtils {
	 
	    public final static String SDCARD_MNT = "/mnt/sdcard";
	    public final static String SDCARD = "/sdcard";
	 
	    /** 请求相册 */
	    public static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0;
	    /** 请求相机 */
	    public static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
	    /** 请求裁剪 */
	    public static final int REQUEST_CODE_GETIMAGE_BYCROP = 2;
	 
	    /**
	     * 写图片文件 在Android系统中,文件保存在 /data/data/PACKAGE_NAME/files 目录下
	     * 
	     * @throws IOException
	     */
	    public static void saveImage(Context context, String fileName, Bitmap bitmap)
	            throws IOException {
	        saveImage(context, fileName, bitmap, 100);
	    }
	 
	    public static void saveImage(Context context, String fileName,
	            Bitmap bitmap, int quality) throws IOException {
	        if (bitmap == null || fileName == null || context == null)
	            return;
	 
	        FileOutputStream fos = context.openFileOutput(fileName,
	                Context.MODE_PRIVATE);
	        ByteArrayOutputStream stream = new ByteArrayOutputStream();
	        bitmap.compress(CompressFormat.JPEG, quality, stream);
	        byte[] bytes = stream.toByteArray();
	        fos.write(bytes);
	        fos.close();
	    }
	 
	    /**
	     * 写图片文件到SD卡
	     * 
	     * @throws IOException
	     */
	    public static void saveImageToSD(Context ctx, String filePath,
	            Bitmap bitmap, int quality) throws IOException {
	        if (bitmap != null) {
	            File file = new File(filePath.substring(0,
	                    filePath.lastIndexOf(File.separator)));
	            if (!file.exists()) {
	                file.mkdirs();
	            }
	            BufferedOutputStream bos = new BufferedOutputStream(
	                    new FileOutputStream(filePath));
	            bitmap.compress(CompressFormat.JPEG, quality, bos);
	            bos.flush();
	            bos.close();
	            if(ctx!=null){
	                scanPhoto(ctx, filePath);
	            }
	        }
	    }
	 
	    /**
	     * 让Gallery上能马上看到该图片
	     */
	    private static void scanPhoto(Context ctx, String imgFileName) {
	        Intent mediaScanIntent = new Intent(
	                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
	        File file = new File(imgFileName);
	        Uri contentUri = Uri.fromFile(file);
	        mediaScanIntent.setData(contentUri);
	        ctx.sendBroadcast(mediaScanIntent);
	    }
	 
	    /**
	     * 获取bitmap
	     * 
	     * @param context
	     * @param fileName
	     * @return
	     */
	    public static Bitmap getBitmap(Context context, String fileName) {
	        FileInputStream fis = null;
	        Bitmap bitmap = null;
	        try {
	            fis = context.openFileInput(fileName);
	            bitmap = BitmapFactory.decodeStream(fis);
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (OutOfMemoryError e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                fis.close();
	            } catch (Exception e) {
	            	e.printStackTrace();
	            }
	        }
	        return bitmap;
	    }
	 
	    /**
	     * 获取bitmap
	     * 
	     * @param filePath
	     * @return
	     */
	    public static Bitmap getBitmapByPath(String filePath) {
	        return getBitmapByPath(filePath, null);
	    }
	 
	    public static Bitmap getBitmapByPath(String filePath,
	            BitmapFactory.Options opts) {
	        FileInputStream fis = null;
	        Bitmap bitmap = null;
	        try {
	            File file = new File(filePath);
	            fis = new FileInputStream(file);
	            bitmap = BitmapFactory.decodeStream(fis, null, opts);
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (OutOfMemoryError e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                fis.close();
	            } catch (Exception e) {
	            }
	        }
	        return bitmap;
	    }
	 
	    /**
	     * 获取bitmap
	     * 
	     * @param file
	     * @return
	     */
	    public static Bitmap getBitmapByFile(File file) {
	        FileInputStream fis = null;
	        Bitmap bitmap = null;
	        try {
	            fis = new FileInputStream(file);
	            bitmap = BitmapFactory.decodeStream(fis);
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (OutOfMemoryError e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                fis.close();
	            } catch (Exception e) {
	            }
	        }
	        return bitmap;
	    }
	 
	    /**
	     * 使用当前时间戳拼接一个唯一的文件名
	     * 
	     * @param format
	     * @return
	     */
	    public static String getTempFileName() {
	        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SS");
	        String fileName = format.format(new Timestamp(System
	                .currentTimeMillis()));
	        return fileName;
	    }
	 
	    /**
	     * 获取照相机使用的目录
	     * 
	     * @return
	     */
	    public static String getCamerPath() {
	        return Environment.getExternalStorageDirectory() + File.separator
	                + "FounderNews" + File.separator;
	    }
	 
	    /**
	     * 判断当前Url是否标准的content://样式,如果不是,则返回绝对路径
	     * 
	     * @param uri
	     * @return
	     */
	    public static String getAbsolutePathFromNoStandardUri(Uri mUri) {
	        String filePath = null;
	 
	        String mUriString = mUri.toString();
	        mUriString = Uri.decode(mUriString);
	 
	        String pre1 = "file://" + SDCARD + File.separator;
	        String pre2 = "file://" + SDCARD_MNT + File.separator;
	 
	        if (mUriString.startsWith(pre1)) {
	            filePath = Environment.getExternalStorageDirectory().getPath()
	                    + File.separator + mUriString.substring(pre1.length());
	        } else if (mUriString.startsWith(pre2)) {
	            filePath = Environment.getExternalStorageDirectory().getPath()
	                    + File.separator + mUriString.substring(pre2.length());
	        }
	        return filePath;
	    }
	 
	    /**
	     * 通过uri获取文件的绝对路径
	     * 
	     * @param uri
	     * @return
	     */
	    public static String getAbsoluteImagePath(Activity context, Uri uri) {
	        String imagePath = "";
	        String[] proj = { MediaStore.Images.Media.DATA };
	        Cursor cursor = context.managedQuery(uri, proj, // Which columns to
	                                                        // return
	                null, // WHERE clause; which rows to return (all rows)
	                null, // WHERE clause selection arguments (none)
	                null); // Order-by clause (ascending by name)
	 
	        if (cursor != null) {
	            int column_index = cursor
	                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	            if (cursor.getCount() > 0 && cursor.moveToFirst()) {
	                imagePath = cursor.getString(column_index);
	            }
	        }
	 
	        return imagePath;
	    }
	 
//	    /**
//	     * 获取图片缩略图 只有Android2.1以上版本支持
//	     * 
//	     * @param imgName
//	     * @param kind
//	     *            MediaStore.Images.Thumbnails.MICRO_KIND
//	     * @return
//	     */
//	    @SuppressWarnings("deprecation")
//		public static Bitmap loadImgThumbnail(Activity context, String imgName,
//	            int kind) {
//	        Bitmap bitmap = null;
//	 
//	        String[] proj = { MediaStore.Images.Media._ID,
//	                MediaStore.Images.Media.DISPLAY_NAME };
//	 
//	        Cursor cursor = context.managedQuery(
//	                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
//	                MediaStore.Images.Media.DISPLAY_NAME + "='" + imgName + "'",
//	                null, null);
//	 
//	        if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
//	            ContentResolver crThumb = context.getContentResolver();
//	            BitmapFactory.Options options = new BitmapFactory.Options();
//	            options.inSampleSize = 1;
//	            bitmap = MethodsCompat.getThumbnail(crThumb, cursor.getInt(0),
//	                    kind, options);
//	        }
//	        return bitmap;
//	    }
	 
	    public static Bitmap loadImgThumbnail(String filePath, int w, int h) {
	        Bitmap bitmap = getBitmapByPath(filePath);
	        return zoomBitmap(bitmap, w, h);
	    }
	 
	    /**
	     * 获取SD卡中最新图片路径
	     * 
	     * @return
	     */
	    public static String getLatestImage(Activity context) {
	        String latestImage = null;
	        String[] items = { MediaStore.Images.Media._ID,
	                MediaStore.Images.Media.DATA };
	        Cursor cursor = context.managedQuery(
	                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, items, null,
	                null, MediaStore.Images.Media._ID + " desc");
	 
	        if (cursor != null && cursor.getCount() > 0) {
	            cursor.moveToFirst();
	            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
	                    .moveToNext()) {
	                latestImage = cursor.getString(1);
	                break;
	            }
	        }
	 
	        return latestImage;
	    }
	 
	    /**
	     * 计算缩放图片的宽高
	     * 
	     * @param img_size
	     * @param square_size
	     * @return
	     */
	    public static int[] scaleImageSize(int[] img_size, int square_size) {
	        if (img_size[0] <= square_size && img_size[1] <= square_size)
	            return img_size;
	        double ratio = square_size
	                / (double) Math.max(img_size[0], img_size[1]);
	        return new int[] { (int) (img_size[0] * ratio),
	                (int) (img_size[1] * ratio) };
	    }
	 
	    /**
	     * 创建缩略图
	     * 
	     * @param context
	     * @param largeImagePath
	     *            原始大图路径
	     * @param thumbfilePath
	     *            输出缩略图路径
	     * @param square_size
	     *            输出图片宽度
	     * @param quality
	     *            输出图片质量
	     * @throws IOException
	     */
	    public static void createImageThumbnail(Context context,
	            String largeImagePath, String thumbfilePath, int square_size,
	            int quality) throws IOException {
	        BitmapFactory.Options opts = new BitmapFactory.Options();
	        opts.inSampleSize = 1;
	        // 原始图片bitmap
	        Bitmap cur_bitmap = getBitmapByPath(largeImagePath, opts);
	 
	        if (cur_bitmap == null)
	            return;
	 
	        // 原始图片的高宽
	        int[] cur_img_size = new int[] { cur_bitmap.getWidth(),
	                cur_bitmap.getHeight() };
	        // 计算原始图片缩放后的宽高
	        int[] new_img_size = scaleImageSize(cur_img_size, square_size);
	        // 生成缩放后的bitmap
	        Bitmap thb_bitmap = zoomBitmap(cur_bitmap, new_img_size[0],
	                new_img_size[1]);
	        // 生成缩放后的图片文件
	        saveImageToSD(null,thumbfilePath, thb_bitmap, quality);
	    }
	 
	    /**
	     * 放大缩小图片
	     * 
	     * @param bitmap
	     * @param w
	     * @param h
	     * @return
	     */
	    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
	        Bitmap newbmp = null;
	        if (bitmap != null) {
	            int width = bitmap.getWidth();
	            int height = bitmap.getHeight();
	            Matrix matrix = new Matrix();
	            float scaleWidht = ((float) w / width);
	            float scaleHeight = ((float) h / height);
	            matrix.postScale(scaleWidht, scaleHeight);
	            newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
	                    true);
	        }
	        return newbmp;
	    }
	 
	    public static Bitmap scaleBitmap(Bitmap bitmap) {
	        // 获取这个图片的宽和高
	        int width = bitmap.getWidth();
	        int height = bitmap.getHeight();
	        // 定义预转换成的图片的宽度和高度
	        int newWidth = 200;
	        int newHeight = 200;
	        // 计算缩放率,新尺寸除原始尺寸
	        float scaleWidth = ((float) newWidth) / width;
	        float scaleHeight = ((float) newHeight) / height;
	        // 创建操作图片用的matrix对象
	        Matrix matrix = new Matrix();
	        // 缩放图片动作
	        matrix.postScale(scaleWidth, scaleHeight);
	        // 旋转图片 动作
	        // matrix.postRotate(45);
	        // 创建新的图片
	        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
	                matrix, true);
	        return resizedBitmap;
	    }
	 
	    /**
	     * (缩放)重绘图片
	     * 
	     * @param context
	     *            Activity
	     * @param bitmap
	     * @return
	     */
	    public static Bitmap reDrawBitMap(Activity context, Bitmap bitmap) {
	        DisplayMetrics dm = new DisplayMetrics();
	        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
	        int rHeight = dm.heightPixels;
	        int rWidth = dm.widthPixels;
	        // float rHeight=dm.heightPixels/dm.density+0.5f;
	        // float rWidth=dm.widthPixels/dm.density+0.5f;
	        // int height=bitmap.getScaledHeight(dm);
	        // int width = bitmap.getScaledWidth(dm);
	        int height = bitmap.getHeight();
	        int width = bitmap.getWidth();
	        float zoomScale;
	        /** 方式1 **/
	        // if(rWidth/rHeight>width/height){//以高为准
	        // zoomScale=((float) rHeight) / height;
	        // }else{
	        // //if(rWidth/rHeight<width height)="" 以宽为准="" zoomscale="((float)" rwidth)="" width;="" }="" **="" 方式2="" if(width*1.5="">= height) {//以宽为准
	        // if(width >= rWidth)
	        // zoomScale = ((float) rWidth) / width;
	        // else
	        // zoomScale = 1.0f;
	        // }else {//以高为准
	        // if(height >= rHeight)
	        // zoomScale = ((float) rHeight) / height;
	        // else
	        // zoomScale = 1.0f;
	        // }
	        /** 方式3 **/
	        if (width >= rWidth)
	            zoomScale = ((float) rWidth) / width;
	        else
	            zoomScale = 1.0f;
	        // 创建操作图片用的matrix对象
	        Matrix matrix = new Matrix();
	        // 缩放图片动作
	        matrix.postScale(zoomScale, zoomScale);
	        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
	                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
	        return resizedBitmap;
	    }
	 
	    /**
	     * 将Drawable转化为Bitmap
	     * 
	     * @param drawable
	     * @return
	     */
	    public static Bitmap drawableToBitmap(Drawable drawable) {
	        int width = drawable.getIntrinsicWidth();
	        int height = drawable.getIntrinsicHeight();
	        Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
	                .getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
	                : Bitmap.Config.RGB_565);
	        Canvas canvas = new Canvas(bitmap);
	        drawable.setBounds(0, 0, width, height);
	        drawable.draw(canvas);
	        return bitmap;
	 
	    }
	 
	    /**
	     * 获得圆角图片的方法
	     * 
	     * @param bitmap
	     * @param roundPx
	     *            一般设成14
	     * @return
	     */
	    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
	 
	        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
	                bitmap.getHeight(), Config.ARGB_8888);
	        Canvas canvas = new Canvas(output);
	 
	        final int color = 0xff424242;
	        final Paint paint = new Paint();
	        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
	        final RectF rectF = new RectF(rect);
	 
	        paint.setAntiAlias(true);
	        canvas.drawARGB(0, 0, 0, 0);
	        paint.setColor(color);
	        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
	 
	        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
	        canvas.drawBitmap(bitmap, rect, rect, paint);
	 
	        return output;
	    }
	 
	    /**
	     * 获得带倒影的图片方法
	     * 
	     * @param bitmap
	     * @return
	     */
	    public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
	        final int reflectionGap = 4;
	        int width = bitmap.getWidth();
	        int height = bitmap.getHeight();
	 
	        Matrix matrix = new Matrix();
	        matrix.preScale(1, -1);
	 
	        Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
	                width, height / 2, matrix, false);
	 
	        Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
	                (height + height / 2), Config.ARGB_8888);
	 
	        Canvas canvas = new Canvas(bitmapWithReflection);
	        canvas.drawBitmap(bitmap, 0, 0, null);
	        Paint deafalutPaint = new Paint();
	        canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);
	 
	        canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
	 
	        Paint paint = new Paint();
	        LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
	                bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
	                0x00ffffff, TileMode.CLAMP);
	        paint.setShader(shader);
	        // Set the Transfer mode to be porter duff and destination in
	        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
	        // Draw a rectangle using the paint with our linear gradient
	        canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
	                + reflectionGap, paint);
	 
	        return bitmapWithReflection;
	    }
	 
	    /**
	     * 将bitmap转化为drawable
	     * 
	     * @param bitmap
	     * @return
	     */
	    public static Drawable bitmapToDrawable(Bitmap bitmap) {
	        Drawable drawable = new BitmapDrawable(bitmap);
	        return drawable;
	    }
	 
	    /**
	     * 获取图片类型
	     * 
	     * @param file
	     * @return
	     */
	    public static String getImageType(File file) {
	        if (file == null || !file.exists()) {
	            return null;
	        }
	        InputStream in = null;
	        try {
	            in = new FileInputStream(file);
	            String type = getImageType(in);
	            return type;
	        } catch (IOException e) {
	            return null;
	        } finally {
	            try {
	                if (in != null) {
	                    in.close();
	                }
	            } catch (IOException e) {
	            }
	        }
	    }
	 
	    /**
	     * 获取图片的类型信息
	     * 
	     * @param in
	     * @return
	     * @see #getImageType(byte[])
	     */
	    public static String getImageType(InputStream in) {
	        if (in == null) {
	            return null;
	        }
	        try {
	            byte[] bytes = new byte[8];
	            in.read(bytes);
	            return getImageType(bytes);
	        } catch (IOException e) {
	            return null;
	        }
	    }
	 
	    /**
	     * 获取图片的类型信息
	     * 
	     * @param bytes
	     *            2~8 byte at beginning of the image file
	     * @return image mimetype or null if the file is not image
	     */
	    public static String getImageType(byte[] bytes) {
	        if (isJPEG(bytes)) {
	            return "image/jpeg";
	        }
	        if (isGIF(bytes)) {
	            return "image/gif";
	        }
	        if (isPNG(bytes)) {
	            return "image/png";
	        }
	        if (isBMP(bytes)) {
	            return "application/x-bmp";
	        }
	        return null;
	    }
	 
	    private static boolean isJPEG(byte[] b) {
	        if (b.length < 2) {
	            return false;
	        }
	        return (b[0] == (byte) 0xFF) && (b[1] == (byte) 0xD8);
	    }
	 
	    private static boolean isGIF(byte[] b) {
	        if (b.length < 6) {
	            return false;
	        }
	        return b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8'
	                && (b[4] == '7' || b[4] == '9') && b[5] == 'a';
	    }
	 
	    private static boolean isPNG(byte[] b) {
	        if (b.length < 8) {
	            return false;
	        }
	        return (b[0] == (byte) 137 && b[1] == (byte) 80 && b[2] == (byte) 78
	                && b[3] == (byte) 71 && b[4] == (byte) 13 && b[5] == (byte) 10
	                && b[6] == (byte) 26 && b[7] == (byte) 10);
	    }
	 
	    private static boolean isBMP(byte[] b) {
	        if (b.length < 2) {
	            return false;
	        }
	        return (b[0] == 0x42) && (b[1] == 0x4d);
	    }

	
	
	
	public static Bitmap comp(Bitmap image) {  
	      
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();         
	    image.compress(Bitmap.CompressFormat.JPEG, 90, baos);  
	    if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出    
	        baos.reset();//重置baos即清空baos  
	        image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%,把压缩后的数据存放到baos中  
	    }  
	    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());  
	    BitmapFactory.Options newOpts = new BitmapFactory.Options();  
	    //开始读入图片,此时把options.inJustDecodeBounds 设回true了  
	    newOpts.inJustDecodeBounds = true;  
	    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
	    newOpts.inJustDecodeBounds = false;  
	    int w = newOpts.outWidth;  
	    int h = newOpts.outHeight;  
	    //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为  
	    float hh = 800f;//这里设置高度为800f  
	    float ww = 480f;//这里设置宽度为480f  
	    //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可  
	    int be = 1;//be=1表示不缩放  
	    if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
	        be = (int) (newOpts.outWidth / ww);  
	    } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放  
	        be = (int) (newOpts.outHeight / hh);  
	    }  
	    if (be <= 0)  
	        be = 1;  
	    newOpts.inSampleSize = be;//设置缩放比例  
	    //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了  
	    isBm = new ByteArrayInputStream(baos.toByteArray());  
	    bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
	    return compressImage(bitmap);//压缩好比例大小后再进行质量压缩  
	} 
	public static Bitmap compressImage(Bitmap image) {  
		if(image == null) return null;
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		newOpts.inJustDecodeBounds = true;// 如果值设为true,那么将不返回实际的bitmap,也不给其分配内存空间,这样就避免了内存溢出。
//		newOpts.inPreferredConfig = Bitmap.Config.ARGB_4444;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中  
        int options = 100;  
        while ( baos.toByteArray().length / 1024>300) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩         
            baos.reset();//重置baos即清空baos  
            if(options < 0) options = 100;
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中  
            options -= 10;//每次都减少10  
        }  
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中  
        newOpts.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);//把ByteArrayInputStream数据生成图片  
        return bitmap;  
    }
	
}

package com.angelonline.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
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.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.StatFs;
import android.provider.MediaStore;
import android.widget.Toast;

public class FileUtil {

	public static String getFilePathByUri(Context context, Uri uri) {
		if (context.getContentResolver() == null) {
			return null;
		}
		try {
			Cursor cursor = context.getContentResolver().query(uri,
					new String[] { MediaStore.MediaColumns.DATA }, null, null,
					null);
			if(cursor == null && uri.getScheme().equals("file")){
				return uri.getEncodedPath();
			}else if(cursor == null){
				return null;
			}else{
				int column = cursor
						.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
				cursor.moveToFirst();
				return cursor.getString(column);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取app对应的文件夹(若没有就创建它)
	 * 
	 * @param context
	 * @return
	 */
	public static File getAppPath(Context context) {

		if (ExistSDCard()) {
			String path = Environment.getExternalStorageDirectory()
					.getAbsolutePath()
					+ File.separator
					+ "angelonline"
					+ File.separator;
			File appFile = new File(path);
			if (!appFile.exists())
				appFile.mkdirs();
			return appFile;
		} else {
			return null;
		}

	}

	/**
	 * 获得照片管理根目录
	 * 
	 * @param context
	 * @return
	 */
	public static File getPhotoDir(Context context) {
		String appPath = getAppPath(context).getAbsolutePath();
		String photoDirPath = appPath + File.separator + "photos"
				+ File.separator;
		File file = new File(photoDirPath);
		if (!file.exists())
			file.mkdirs();
		return file;
	}

	
	public static void mkdir(String path){
		mkdir(new File(path));
	}
	
	public static void mkdir(File file){
		if(!file.exists())
			file.mkdirs();
	}
	
	/**
	 * 检测是否有sd卡
	 * 
	 * @return
	 */
	public static boolean ExistSDCard() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else
			return false;
	}

	/**
	 * sd卡剩余容量
	 * 
	 * @return 单位MB
	 */
	public static long getSDFreeSize() {
		// 取得SD卡文件路径
		File path = Environment.getExternalStorageDirectory();
		StatFs sf = new StatFs(path.getPath());
		// 获取单个数据块的大小(Byte)
		long blockSize = sf.getBlockSize();
		// 空闲的数据块的数量
		long freeBlocks = sf.getAvailableBlocks();
		// 返回SD卡空闲大小
		// return freeBlocks * blockSize; //单位Byte
		// return (freeBlocks * blockSize)/1024; //单位KB
		return (freeBlocks * blockSize) / 1024 / 1024; // 单位MB
	}


	/**
	 * 创建下一级文件
	 * 
	 * @param parentFile
	 *            父文件
	 * @param childFileName
	 *            子文件名
	 * @return 如果文件存在return false,否则return true;
	 */
	public static boolean createFile(File parentFile, String childFileName) {
		String path = parentFile.getAbsolutePath() + File.separator
				+ childFileName + File.separator;
		File tempFile = new File(path);
		if (tempFile.exists()) {
			return false;
		} else {
			tempFile.mkdirs();
			return true;
		}
	}

	

	/**
	 * 复制单个文件
	 * 
	 * @param oldPath
	 *            String 原文件路径 如:c:/fqf.txt
	 * @param newPath
	 *            String 复制后路径 如:f:/fqf.txt
	 * @return boolean
	 */
	public static void copyFile(String oldPath, String newPath) {
		if(!oldPath.endsWith("/"))
			oldPath = oldPath+"/";
		InputStream inStream = null;
		FileOutputStream fs = null;
		try {
			int bytesum = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在时
				inStream = new FileInputStream(oldPath); // 读入原文件
				fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				int length;
				int byteread = 0;
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
			}
		} catch (Exception e) {
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();

		} finally {

			try {
				if(inStream!=null)
				inStream.close();
				if(fs!=null)
				fs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 复制整个文件夹内容
	 * 
	 * @param oldPath
	 *            String 原文件路径 如:c:/fqf
	 * @param newPath
	 *            String 复制后路径 如:f:/fqf/ff
	 * @return boolean
	 */
	public static void copyFolder(Context context, String oldPath,
			String newPath) throws Exception {

		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹

			// File noteFile = new File(newPath);
			// outputNote(noteFile,context);

			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}

				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath
							+ "/" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory()) {// 如果是子文件夹
					copyFolder(context, oldPath + "/" + file[i], newPath + "/"
							+ file[i]);
				}
			}
		} catch (Exception e) {
			System.out.println("复制整个文件夹内容操作出错");
			e.printStackTrace();

		}

	}

	/**
	 * 复制整个文件夹内容
	 * 
	 * @param oldPath
	 *            String 原文件路径 如:c:/fqf
	 * @param newPath
	 *            String 复制后路径 如:f:/fqf/ff
	 * @return boolean
	 */
	public void copyFolder(String oldPath, String newPath) {

		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}

				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath
							+ "/" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory()) {// 如果是子文件夹
					copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
				}
			}
		} catch (Exception e) {
			System.out.println("复制整个文件夹内容操作出错");
			e.printStackTrace();

		}

	}


	public static void deleteFile(File file) {
		
		if(!file.exists())
			return;
		
		File[] fileArray = file.listFiles();
		
		if (fileArray.length > 0) {
			for (int i = 0; i < fileArray.length; i++) {
				if (fileArray[i].isFile()) {
					if (fileArray[i].delete()) {
						System.out.println("删除成功");
					} else {
						System.out.println("删除不成功");
					}
				} else {
					deleteFile(fileArray[i]);
				}
			}
		}
		
		file.delete();
	}
	
	
	public static void unZip(String path)   
    {  
		final int buffer = 2048; 
        int count = -1;  
        int index = -1;  
          
        String savepath = "";  
//        boolean flag = false;  
          
        savepath = path.substring(0, path.lastIndexOf("\\")) + "\\";  
  
        try   
        {  
            BufferedOutputStream bos = null;  
            ZipEntry entry = null;  
            FileInputStream fis = new FileInputStream(path);   
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));  
              
            while((entry = zis.getNextEntry()) != null)   
            {  
                byte data[] = new byte[buffer];   
  
                String temp = entry.getName();  
                  
//                flag = isPics(temp);  
//                if(!flag)  
//                    continue;  
                  
                index = temp.lastIndexOf("/");  
                if(index > -1)  
                    temp = temp.substring(index+1);  
                temp = savepath + temp;  
                  
                File f = new File(temp);  
                f.createNewFile();  
  
                FileOutputStream fos = new FileOutputStream(f);  
                bos = new BufferedOutputStream(fos, buffer);  
                  
                while((count = zis.read(data, 0, buffer)) != -1)   
                {  
                    bos.write(data, 0, count);  
                }  
  
                bos.flush();  
                bos.close();  
            }  
  
            zis.close();  
  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值