记DataOutputStream和DataInputStream的一用法

java中如何将多个文件从一个服务器发送到另外一个服务器,关键代码如下:

发送端代码

import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.client.methods.HttpPost;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
public @ResponseBody String uploadFiles(HttpServletRequest request, HttpServletResponse response)  throws Exception {
	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
	
	List<byte[]> fileByteArrList = null;
	for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
		// 上传文件
		MultipartFile mf = entity.getValue();
		if (fileByteArrList == null) {
			fileByteArrList = new ArrayList<byte[]>();
		}
		fileByteArrList.add(mf.getBytes());
				
	}
	if (fileByteArrList == null) {
		return "请上传文件";
	}
	//将多个文件装入到DataOutputStream
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	DataOutputStream dos = new DataOutputStream(bos);
	for(byte[] bt : clazzes){
		dos.writeInt(bt.length);
		dos.write(bt);
	}
	byte[] fileByteArray = bos.toByteArray();
	send(/*这里的url简略*/url, fileByteArray);

	return "发送成功";
}

public String post(String url, byte[] paramByte) throws Exception {
	HttpPost httpPost = new HttpPost(url);
	httpPost.setEntity(new ByteArrayEntity(paramByte));
	return httpclient.execute(httpPost, responseHandler);
}

接收端代码

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;

@RequestMapping(value = "/acceptFiles", method = RequestMethod.POST)
public @ResponseBody String acceptFiles(HttpServletRequest request, HttpServletResponse response)  throws Exception {
	/**简略掉如何从request中取到byte[] fileByteArray**/
	
    //从DataInputStream中转换出来
	ByteArrayInputStream bis = new ByteArrayInputStream(fileByteArray);
	DataInputStream dis = new DataInputStream(bis);
	int count = 0;
	List<byte[]> fileByteList = new ArrayList<>();
	while (count < fileByteArray.length) {
		int length = dis.readInt();
		count += 4;
		byte[] bb = new byte[length];
		count += dis.read(bb);
		fileByteList.add(bb);
	}

	//最终行到fileByteList,下面就是业务操作了
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

没出过地球

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值