java 依据File图片文件对象或者http图片文件url将图片文件写到服务器

背景:项目中需要依据上传的图片或者贴在文本框的图片地址url,获得图片文件,并将图片生成到服务器指定目录

先上代码

package com.eelly.imagesearch.common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class FileCommendDeal {
	
	/**
	 * 将文件file写入到指定的目录中
	 * @param file
	 * @param path
	 * @param fileName
	 * @return 写完后的文件地址
	 */
	public String writeFileToPath(File file, String path, String fileName)
	{
	    // 文件成功写入到指定存放目录
	    String successsWriteFileName = "";
		
	    Random random = new Random();
		
	    //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
	    String tempName = df.format(new Date())+random.nextInt(10000)+"."+fileName;
	    String filePath = path+"/"+tempName;
		
	    FileChannel in = null;  
	    FileChannel out = null;  
	    FileInputStream inStream = null;  
	    FileOutputStream outStream = null;  
	    try {  
	        inStream = new FileInputStream(file);  
	        // 用filePath创建一个空文件将file文件流写入
	        File writeFile = new File(filePath);
	        if (!writeFile.exists())
	        {
	        	writeFile.createNewFile();
	        }
	        outStream = new FileOutputStream(writeFile);  
	        in = inStream.getChannel();  
	        out = outStream.getChannel();  
	        in.transferTo(0, in.size(), out);  
	        in.close();
	        inStream.close();
	        out.close();
	        outStream.close();
	        successsWriteFileName = tempName;
	    } catch (IOException e) {
	    	successsWriteFileName = "";
	        e.printStackTrace();
	    }
		return successsWriteFileName;
	}
	
	/**
	 * 将http请求获得的流写入到指定的目录中
	 * @param file
	 * @param path
	 * @param fileName
	 * @return 写完后的文件地址
	 */
	public String writeHttpImgToPath(String imgurl, String path, String fileType)
	{
		// 文件成功写入到指定存放目录
		String successsWriteFileName = "";
		Random random = new Random();
		
		// 设置日期格式
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String tempName = df.format(new Date())+random.nextInt(10000)+"."+fileType;
		String filePath = path+"/"+tempName;
		
	    try {
	    	//new一个URL对象  
		URL url = new URL(imgurl);  
		//打开链接  
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
		//设置请求方式为"GET"  
		conn.setRequestMethod("GET");  
		//超时响应时间为5秒  
		conn.setConnectTimeout(5 * 1000);  
		//通过输入流获取图片数据  
		InputStream inputio = conn.getInputStream();
			
		//创建一个输出流
	    	ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();  
	        //创建一个Buffer字符串  
	        byte[] buffer = new byte[1024];  
	        //每次读取的字符串长度,如果为-1,代表全部读取完毕  
	        int len = 0;  
	        //使用一个输入流从buffer里把数据读取出来  
	        while( (len=inputio.read(buffer)) != -1 ){  
	            // 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度  
	        	byteOutStream.write(buffer, 0, len);  
	        }  
	        // 关闭输入流  
	        inputio.close();
	        
	        // 得到图片的二进制数据,以二进制封装得到数据,具有通用性
	        byte[] data = byteOutStream.toByteArray();  
	        // 依据指定目录文件new一个文件对象用来保存图片 
	        File imageFile = new File(filePath);  
	        // 创建输出流  
	        FileOutputStream outStream = new FileOutputStream(imageFile);  
	        // 写入数据  
	        outStream.write(data);  
	        // 关闭输出流  
	        outStream.close(); 
	        successsWriteFileName = filePath;
	    } catch (IOException e) {
	    	successsWriteFileName = "";
	        e.printStackTrace();
	    }
		return successsWriteFileName;
	}
}
备注:

1.生成的文件随机名格式:日期+随机四位数+后缀名

2.开流后需要记得在用完后需要关掉

3.流操作,文件操作记得try...catch监视下,或者在方法定义的时候throw抛出异常,在调用的地方做try...catch也可以

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值