JAVA代码上传文件

来源:互联网 发布:淘宝开店要哪些软件 编辑:程序博客网 时间:2024/06/03 02:37

package com.drowcrm.service.blacklist.util;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


import com.drowcrm.service.system.exception.SystemException;

public class UploadUtil {
    /**上传文件缓冲区的大小*/
    public static final int UPLOAD_BUFFER_SIZE = 8192;
   
    public static void upload(InputStream fis, String toFilePath) throws SystemException {
          BufferedInputStream stream = null;
          BufferedOutputStream bos = null;
          try {
           //获取上传的文件
           stream = new BufferedInputStream(fis);        //把文件读入  
              bos = new BufferedOutputStream(new FileOutputStream(toFilePath));//建立一个上传文件的输出流
            
              int bytesRead = 0;
              byte[] buffer = new byte[UPLOAD_BUFFER_SIZE];
              while ((bytesRead = stream.read(buffer, 0, UPLOAD_BUFFER_SIZE)) != -1) {
                  bos.write(buffer, 0, bytesRead);      //将文件写入服务器
              }
              stream.close();
              bos.close();
          } catch (Exception e) {            
              throw new SystemException("文件上传错误", e);
          } finally {
              try {
                if (stream != null) stream.close();
                  if (bos != null) bos.close();
            } catch (IOException e) {
                throw new SystemException("文件关闭错误", e);
            }
          }
       
    }
 
}

0 0
原创粉丝点击