爱编程的欧巴

让我们成长吧~
  博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

文件上传工具类 UploadUtil.java

Posted on 2016-01-29 13:26  爱编程的欧巴  阅读(819)  评论(0编辑  收藏  举报
  1. package com.util;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileOutputStream;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10. import java.util.Calendar;  
  11.   
  12. /** 
  13.  * 文件上传工具类 
  14.  * 
  15.  */  
  16. public class UploadUtil {  
  17.     private static final int BUFFER_SIZE = 16 * 1024;  
  18.     //保存图片  
  19.     public static synchronized void copy(File src, File newFile) {  
  20.           
  21.         try {  
  22.             InputStream is = null;  
  23.             OutputStream os = null;  
  24.             try {  
  25.                 is = new BufferedInputStream(new FileInputStream(src),  
  26.                         BUFFER_SIZE);  
  27.                 os = new BufferedOutputStream(new FileOutputStream(newFile),  
  28.                         BUFFER_SIZE);  
  29.                 byte[] buffer = new byte[BUFFER_SIZE];  
  30.                 while (is.read(buffer) > 0) {  
  31.                     os.write(buffer);  
  32.                 }  
  33.             } finally {  
  34.                 if (null != is) {  
  35.                     is.close();  
  36.                 }  
  37.                 if (null != os) {  
  38.                     os.close();  
  39.                 }  
  40.             }  
  41.         } catch (Exception e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.     }  
  45.   
  46.     /** 
  47.      * 返回 年号+月号+天+时+分+秒+随机码 
  48.      * @return 
  49.      */  
  50.     @SuppressWarnings("static-access")  
  51.     public static synchronized String getTime() {  
  52.         Calendar calendar = Calendar.getInstance();  
  53.         String year = calendar.get(calendar.YEAR) + "";  
  54.         String month = (calendar.get(calendar.MONTH) + 1) + "";  
  55.         String day = calendar.get(calendar.DAY_OF_MONTH) + "";  
  56.         String hour = calendar.get(calendar.HOUR_OF_DAY) + "";  
  57.         String minute = calendar.get(calendar.MINUTE) + "";  
  58.         String second = calendar.get(calendar.SECOND) + "";  
  59.         String milliSecond = calendar.get(calendar.MILLISECOND) + "";  
  60.         int r = (int)(Math.random()*100000);  
  61.         String random = String.valueOf(r);  
  62.         return year + month + day + hour + minute + second + milliSecond + random+"a";  
  63.     }  
  64.   
  65. }