package com.sandu.ximon.admin.manager.iot.rrpc.util; import com.sandu.ximon.admin.dto.RemoteFileDto; import com.sandu.ximon.admin.utils.HexUtils; import com.sandu.ximon.admin.utils.StringUtil; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author ZZQ * @date 2022/5/5 14:26 */ public class FileProcessingUtils { private static final int readSize = 512; public static RemoteFileDto read(String filePath) { //文件地址为空 if (filePath == null) { return null; } List data = new ArrayList<>(); // 取数据长度 int dataSize = 0; StringBuffer fileHexStr = new StringBuffer(); try { // 创建URL URL url = new URL(filePath); // 试图连接并取得返回状态码 URLConnection urlconn = url.openConnection(); urlconn.connect(); HttpURLConnection httpconn = (HttpURLConnection) urlconn; int HttpResult = httpconn.getResponseCode(); if (HttpResult != HttpURLConnection.HTTP_OK) { System.out.print("无法连接到"); return null; } else { InputStream in = urlconn.getInputStream(); // 一次性取多少个字节 byte[] bytes = new byte[readSize]; // 读取到的字节数组长度,为-1时表示没有数据 int length = 0; // 循环取数据 while ((length = in.read(bytes)) != -1) { String temp = HexUtils.encodeHexStr(Arrays.copyOf(bytes, length)); if (!StringUtil.strIsNullOrEmpty(temp)) { fileHexStr.append(temp); dataSize += length; } } in.close(); //按每帧数据大小进行切割截取数据 String tempHexStr = fileHexStr.toString(); int c = readSize * 2; int cl = -1; while (!StringUtil.strIsNullOrEmpty(tempHexStr)) { if (tempHexStr.length() > c) { cl = c; } else { cl = tempHexStr.length(); } data.add(tempHexStr.substring(0, cl)); tempHexStr = tempHexStr.substring(cl, tempHexStr.length()); } RemoteFileDto remoteFileDto = new RemoteFileDto(); remoteFileDto.setList(data); remoteFileDto.setListSize(dataSize); remoteFileDto.setFileHexStr(fileHexStr.toString()); return remoteFileDto; } } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) { RemoteFileDto t = read("https://ximonsmart.oss-cn-shanghai.aliyuncs.com/20220507175550f1c437-e2f6-413f-9a78-c1cfea3d2a82.bin"); System.out.println(t.getListSize()); System.out.println(t.getList().size()); } }