Android中常用的工具类总结

1.文件操作工具类

     /**
     * 以文件流的方式复制文件
     * @param src 文件源目录
     * @param dest 文件目的目录
     * @throws IOException  
     */
    public static void copyFile(String src,String dest) throws IOException{
        FileInputStream in=new FileInputStream(src);
        File file=new File(dest);
        if(!file.exists())
            file.createNewFile();
        FileOutputStream out=new FileOutputStream(file);
        int c;
        byte buffer[]=new byte[1024];
        while((c=in.read(buffer))!=-1){
            for(int i=0;i<c;i++)
                out.write(buffer[i]);        
        }
        in.close();
        out.close();
    }
    
    /**
     * 利用PrintStream写文件
     * @param src 写入文件的路径
     */
    public static void PrintStreamOut(String src,String contents){
    	try {
    		FileOutputStream out=new FileOutputStream(src);
    		PrintStream p=new PrintStream(out);
    		for(int i=0;i<contents.length();i++)
    			p.print(contents.charAt(i));
    	} catch (FileNotFoundException e) {
    		e.printStackTrace();
    	}
    } 
    
    /**
     * 利用PrintStream写文件
     * @param src 写入文件的路径
     */
    public static void StringBufferOut(String src,String contents) throws IOException{
        File file=new File(src);
        if(!file.exists())
            file.createNewFile();
        FileOutputStream out=new FileOutputStream(file,true);        
        for(int i=0;i<contents.length();i++){
            StringBuffer sb=new StringBuffer();
            sb.append(contents.charAt(i));
            out.write(sb.toString().getBytes("utf-8"));
        }        
        out.close();
    }
    
    /**
     * 文件重命名
     * @param path 文件目录
     * @param oldname  原来的文件名
     * @param newname 新文件名
     * @param num 已存在该文件名
     */
    public static void renameFile(String path,String oldname,String newname,int num,String suffix){
        if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名
            File oldfile=new File(path+"/"+oldname);
            File newfile = null;
            String temp = newname;
            if(num==0){
            	newname = newname+suffix;
            	newfile=new File(path+"/"+newname);
            }else{
            	newname = newname+num+suffix;
            	newfile=new File(path+"/"+newname);
            }
            if(newfile.exists()){//若在该目录下已经有一个文件和新文件名相同,则命名为newname1.2.3...
            	num++;
                renameFile(path,oldname,temp,num,suffix);
            }else{
                oldfile.renameTo(newfile);
            } 
        }         
    }
    /**
     * 转移文件目录
     * @param filename 文件名
     * @param oldpath 旧目录
     * @param newpath 新目录
     * @param cover 若新目录下存在和转移文件具有相同文件名的文件时,是否覆盖新目录下文件,cover=true将会覆盖原文件,否则不操作
     */
    public static void changeDirectory(String filename,String oldpath,String newpath,boolean cover){
        if(!oldpath.equals(newpath)){
            File oldfile=new File(oldpath+"/"+filename);
            File newfile=new File(newpath+"/"+filename);
            if(newfile.exists()){//若在待转移目录下,已经存在待转移文件
                if(cover){//覆盖
                	newfile.delete();
                    oldfile.renameTo(newfile);
                }else
                    System.out.println("在新目录下已经存在:"+filename);
            }
            else{
                oldfile.renameTo(newfile);
            }
        }       
    }

/**
     * @author LiZhen
     * @param strFile
     * @throws Exception
     */
    public static void UnZip(String strFile) throws Exception {
	// 输出文件夹
    	String baseDir = "d:\";
    	ZipFile zFile = new ZipFile(strFile);
    	System.out.println(zFile.getName());
    	Enumeration en = zFile.entries();
    	ZipEntry entry = null;
    	while (en.hasMoreElements()) {
    		// 得到其中一项ZipEntry
    		entry = (ZipEntry) en.nextElement();
    		// 如果是文件夹则不处理
    		if (entry.isDirectory()) {
    			System.out.println("Dir: " + entry.getName() + " skipped..");
    		} else {
    			// 如果是文件则写到输出目录
    			copyFile(zFile, baseDir, entry);		
    		}
    	}
    	zFile.close();
    }

    private static void copyFile(ZipFile source, String baseDir, ZipEntry entry)
	    throws Exception {
    	// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
    	// 是否需要创建目录
    	mkdirs(baseDir, entry.getName());
    	// 建立输出流
    	OutputStream os = new BufferedOutputStream(new FileOutputStream(
    			new File(baseDir, entry.getName())));
    	// 取得对应ZipEntry的输入流
    	InputStream is = new BufferedInputStream(source.getInputStream(entry));
    	int readLen = 0;
    	byte[] buf = new byte[1024];
    	// 复制文件
    	System.out.println("Extracting: " + entry.getName() + "t"
    			+ entry.getSize() + "t" + entry.getCompressedSize());
    	while ((readLen = is.read(buf, 0, 1024)) != -1) {
    		os.write(buf, 0, readLen);
    	}
    	is.close();
    	os.close();
    	System.out.println("Extracted: " + entry.getName());
    }

    /**
     * 给定根目录,返回一个相对路径所对应的实际文件名.
     * 
     * @param baseDir
     *                指定根目录
     * @param absFileName
     *                相对路径名,来自于ZipEntry中的name
     * @return java.io.File 实际的文件
     */
    private static void mkdirs(String baseDir, String relativeFileName) {
    	String[] dirs = relativeFileName.split("/");
    	File ret = new File(baseDir);
    	if (dirs.length > 1) {
    		for (int i = 0; i < dirs.length - 1; i++) {
    			ret = new File(ret, dirs[i]);
    		}
    	}
    	if (!ret.exists()) {
    		ret.mkdirs();
    	}
    }


2.Bitmap与DrawAble与byte[]与InputStream之间的转换工具类

package com.soai.imdemo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

/**
 * Bitmap与DrawAble与byte[]与InputStream之间的转换工具类
 * @author Administrator
 *
 */
public class FormatTools {
	private static FormatTools tools = new FormatTools();

	public static FormatTools getInstance() {
		if (tools == null) {
			tools = new FormatTools();
			return tools;
		}
		return tools;
	}

	// 将byte[]转换成InputStream
	public InputStream Byte2InputStream(byte[] b) {
		ByteArrayInputStream bais = new ByteArrayInputStream(b);
		return bais;
	}

	// 将InputStream转换成byte[]
	public byte[] InputStream2Bytes(InputStream is) {
		String str = "";
		byte[] readByte = new byte[1024];
		int readCount = -1;
		try {
			while ((readCount = is.read(readByte, 0, 1024)) != -1) {
				str += new String(readByte).trim();
			}
			return str.getBytes();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 将Bitmap转换成InputStream
	public InputStream Bitmap2InputStream(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		InputStream is = new ByteArrayInputStream(baos.toByteArray());
		return is;
	}

	// 将Bitmap转换成InputStream
	public InputStream Bitmap2InputStream(Bitmap bm, int quality) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, quality, baos);
		InputStream is = new ByteArrayInputStream(baos.toByteArray());
		return is;
	}

	// 将InputStream转换成Bitmap
	public Bitmap InputStream2Bitmap(InputStream is) {
		return BitmapFactory.decodeStream(is);
	}

	// Drawable转换成InputStream
	public InputStream Drawable2InputStream(Drawable d) {
		Bitmap bitmap = this.drawable2Bitmap(d);
		return this.Bitmap2InputStream(bitmap);
	}

	// InputStream转换成Drawable
	public Drawable InputStream2Drawable(InputStream is) {
		Bitmap bitmap = this.InputStream2Bitmap(is);
		return this.bitmap2Drawable(bitmap);
	}

	// Drawable转换成byte[]
	public byte[] Drawable2Bytes(Drawable d) {
		Bitmap bitmap = this.drawable2Bitmap(d);
		return this.Bitmap2Bytes(bitmap);
	}

	// byte[]转换成Drawable
	public Drawable Bytes2Drawable(byte[] b) {
		Bitmap bitmap = this.Bytes2Bitmap(b);
		return this.bitmap2Drawable(bitmap);
	}

	// Bitmap转换成byte[]
	public byte[] Bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	// byte[]转换成Bitmap
	public Bitmap Bytes2Bitmap(byte[] b) {
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		}
		return null;
	}

	// Drawable转换成Bitmap
	public Bitmap drawable2Bitmap(Drawable drawable) {
		Bitmap bitmap = Bitmap
				.createBitmap(
						drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight(),
						drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
								: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}

	// Bitmap转换成Drawable
	public Drawable bitmap2Drawable(Bitmap bitmap) {
		BitmapDrawable bd = new BitmapDrawable(bitmap);
		Drawable d = (Drawable) bd;
		return d;
	}
}



3.其它常用工具类

一. 检查网络是否可用.

ConnectionUtil.java

[java]  view plain copy
  1. import android.app.AlertDialog;  
  2. import android.content.Context;  
  3. import android.content.DialogInterface;  
  4. import android.net.ConnectivityManager;  
  5. import android.net.NetworkInfo;  
  6.   
  7.   
  8. public class ConnectionUtil {  
  9. /** 
  10. * 检查网络是否可用 
  11. * @param context 
  12. 应用程序的上下文对象 
  13. * @return 
  14. */  
  15. public static boolean isNetworkAvailable(Context context) {  
  16. ConnectivityManager connectivity = (ConnectivityManager) context  
  17. .getSystemService(Context.CONNECTIVITY_SERVICE);  
  18. //获取系统网络连接管理器  
  19. if (connectivity == null) {  
  20. //如果网络管理器为null  
  21. return false;  //返回false表明网络无法连接  
  22. else {  
  23. NetworkInfo[] info = connectivity.getAllNetworkInfo();  
  24. //获取所有的网络连接对象  
  25. if (info != null) {  
  26. //网络信息不为null时  
  27. for (int i = 0; i < info.length; i++) {  
  28. //遍历网路连接对象  
  29. if (info[i].isConnected()) {  
  30. //当有一个网络连接对象连接上网络时  
  31. return true;  //返回true表明网络连接正常  
  32. }   
  33. }  
  34. }  
  35. }  
  36. return false;    
  37. }  
  38.   
  39. public static void httpTest(final Context ctx,String title,String msg) {  
  40. if (!isNetworkAvailable(ctx)) {  
  41. AlertDialog.Builder builders = new AlertDialog.Builder(ctx);  
  42. builders.setTitle(title);  
  43. builders.setMessage(msg);  
  44. builders.setPositiveButton(android.R.string.ok,  
  45. new DialogInterface.OnClickListener() {  
  46. public void onClick(DialogInterface dialog, int which) {  
  47. //alert.dismiss();  
  48. }  
  49. });  
  50. AlertDialog alert = builders.create();  
  51. alert.show();  
  52. }  
  53. }  
  54. }  


二.读取流文件.

FileStreamTool.java

[java]  view plain copy
  1. import java.io.ByteArrayOutputStream;  
  2. import java.io.File;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.PushbackInputStream;  
  7.   
  8.   
  9. public class FileStreamTool {  
  10.   
  11.   
  12. public static void save(File file, byte[] data) throws Exception {  
  13. FileOutputStream outStream = new FileOutputStream(file);  
  14. outStream.write(data);  
  15. outStream.close();  
  16. }  
  17.    
  18. public static String readLine(PushbackInputStream in) throws IOException {  
  19. char buf[] = new char[128];  
  20. int room = buf.length;  
  21. int offset = 0;  
  22. int c;  
  23. loop: while (true) {  
  24. switch (c = in.read()) {  
  25. case -1:  
  26. case '\n':  
  27. break loop;  
  28. case '\r':  
  29. int c2 = in.read();  
  30. if ((c2 != '\n') && (c2 != -1)) in.unread(c2);  
  31. break loop;  
  32. default:  
  33. if (--room < 0) {  
  34. char[] lineBuffer = buf;  
  35. buf = new char[offset + 128];  
  36.    room = buf.length - offset - 1;  
  37.    System.arraycopy(lineBuffer, 0, buf, 0, offset);  
  38.     
  39. }  
  40. buf[offset++] = (char) c;  
  41. break;  
  42. }  
  43. }  
  44. if ((c == -1) && (offset == 0)) return null;  
  45. return String.copyValueOf(buf, 0, offset);  
  46. }  
  47.    
  48. /** 
  49. * 读取流 
  50. * @param inStream 
  51. * @return 字节数组 
  52. * @throws Exception 
  53. */  
  54. public static byte[] readStream(InputStream inStream) throws Exception{  
  55. ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
  56. byte[] buffer = new byte[1024];  
  57. int len = -1;  
  58. while( (len=inStream.read(buffer)) != -1){  
  59. outSteam.write(buffer, 0, len);  
  60. }  
  61. outSteam.close();  
  62. inStream.close();  
  63. return outSteam.toByteArray();  
  64. }  
  65. }  

三.文件断点续传.

MainActivity.java

[java]  view plain copy
  1. import java.io.File;  
  2. import java.io.OutputStream;  
  3. import java.io.PushbackInputStream;  
  4. import java.io.RandomAccessFile;  
  5. import java.net.Socket;  
  6. import cn.itcast.service.UploadLogService;  
  7. import cn.itcast.utils.StreamTool;  
  8. import android.app.Activity;  
  9. import android.os.Bundle;  
  10. import android.os.Environment;  
  11. import android.os.Handler;  
  12. import android.os.Message;  
  13. import android.view.View;  
  14. import android.widget.Button;  
  15. import android.widget.EditText;  
  16. import android.widget.ProgressBar;  
  17. import android.widget.TextView;  
  18. import android.widget.Toast;  
  19.   
  20.   
  21. public class MainActivity extends Activity {  
  22.     private EditText filenameText;  
  23.     private TextView resultView;  
  24.     private ProgressBar uploadbar;  
  25.     private UploadLogService service;  
  26.     private Handler handler = new Handler(){  
  27. @Override  
  28. public void handleMessage(Message msg) {  
  29. uploadbar.setProgress(msg.getData().getInt("length"));  
  30. float num = (float)uploadbar.getProgress() / (float)uploadbar.getMax();  
  31. int result = (int)(num * 100);  
  32. resultView.setText(result + "%");  
  33. if(uploadbar.getProgress() == uploadbar.getMax()){  
  34. Toast.makeText(MainActivity.this, R.string.success, 1).show();  
  35. }  
  36. }  
  37.     };  
  38.       
  39.     @Override  
  40.     public void onCreate(Bundle savedInstanceState) {  
  41.         super.onCreate(savedInstanceState);  
  42.         setContentView(R.layout.main);  
  43.           
  44.         service =  new UploadLogService(this);  
  45.         filenameText = (EditText)findViewById(R.id.filename);  
  46.         resultView = (TextView)findViewById(R.id.result);  
  47.         uploadbar = (ProgressBar)findViewById(R.id.uploadbar);  
  48.         Button button = (Button)findViewById(R.id.button);  
  49.         button.setOnClickListener(new View.OnClickListener() {  
  50.   
  51. public void onClick(View v) {  
  52. String filename = filenameText.getText().toString();  
  53. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
  54. File file = new File(Environment.getExternalStorageDirectory(), filename);  
  55. if(file.exists()){  
  56. uploadbar.setMax((int)file.length());  
  57. uploadFile(file);  
  58. }else{  
  59. Toast.makeText(MainActivity.this, R.string.notexsit, 1).show();  
  60. }  
  61. }else{  
  62. Toast.makeText(MainActivity.this, R.string.sdcarderror, 1).show();  
  63. }  
  64. }  
  65. });  
  66.     }  
  67.   
  68.   
  69. private void uploadFile(final File file) {  
  70. new Thread(new Runnable() {  
  71.   
  72. public void run() {  
  73. try {  
  74. String sourceid = service.getBindId(file);  
  75. Socket socket = new Socket("192.168.1.100"7878);//根据IP地址和端口不同更改  
  76.            OutputStream outStream = socket.getOutputStream();   
  77.            String head = "Content-Length="+ file.length() + ";filename="+ file.getName()   
  78.              + ";sourceid="+(sourceid!=null ? sourceid : "")+"\r\n";  
  79.            outStream.write(head.getBytes());  
  80.              
  81.            PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());  
  82.   
  83. String response = StreamTool.readLine(inStream);  
  84.            String[] items = response.split(";");  
  85. String responseSourceid = items[0].substring(items[0].indexOf("=")+1);  
  86. String position = items[1].substring(items[1].indexOf("=")+1);  
  87. if(sourceid==null){ //如果是第一次上传文件,在数据库中不存在该文件所绑定的资源id,入库  
  88. service.save(responseSourceid, file);  
  89. }  
  90. RandomAccessFile fileOutStream = new RandomAccessFile(file, "r");  
  91. fileOutStream.seek(Integer.valueOf(position));  
  92. byte[] buffer = new byte[1024];  
  93. int len = -1;  
  94. int length = Integer.valueOf(position);  
  95. while( (len = fileOutStream.read(buffer)) != -1){  
  96. outStream.write(buffer, 0, len);  
  97. length += len;//累加已经上传的数据长度  
  98. Message msg = new Message();  
  99. msg.getData().putInt("length", length);  
  100. handler.sendMessage(msg);  
  101. }  
  102. if(length == file.length()) service.delete(file);  
  103. fileOutStream.close();  
  104. outStream.close();  
  105.            inStream.close();  
  106.            socket.close();  
  107.        } catch (Exception e) {                      
  108.          Toast.makeText(MainActivity.this, R.string.error, 1).show();  
  109.        }  
  110. }  
  111. }).start();  
  112. }  
  113. }  

DBOpenHelper.java

[java]  view plain copy
  1. import android.content.Context;  
  2. import android.database.sqlite.SQLiteDatabase;  
  3. import android.database.sqlite.SQLiteOpenHelper;  
  4.   
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值