java文件上传方法

public class UploadUtils {    
    /**
     * 根据文件路径,上传文件 
     * @param sourcePath 源文件路径和名字
     * @param targetPath 目标文件路径和名字
     * @param maxFileSize 文件大小
     * @return 布尔值
     */
    public static boolean uploadFile(String sourcePath, String targetPath, int maxFileSize){
    		
    	 try {
    		 InputStream stream = new FileInputStream(sourcePath);
    		 System.out.println(stream.available());
    		 if(stream.available()<maxFileSize*1024){
             OutputStream bos = new FileOutputStream(targetPath);
             byte[] buffer = new byte[8192];
             int bytesRead = 0;
             while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                 bos.write(buffer, 0, bytesRead);
             }
             bos.close();
             stream.close();
    		 }else{
    			 return false;
    		 }
         }
         catch(Exception e){
        	 e.printStackTrace();
        	 return false;
             
         }
         return true;
    }

}  

你可能感兴趣的:(java)