package com.fzzy.api.utils; import com.fzzy.data.ConfigData; import org.apache.commons.lang.time.DateFormatUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; /** * 将文件转为二进制流工具类 * @author czt * */ @Service(FileUtils.BEAN_ID) public class FileUtils { public static final String BEAN_ID = "base.fileUtil"; @Autowired private ConfigData configData; /** * 根据文件路径将文件转为二进制文件流字符串 * @param filePath:文件路径 * @return */ public static String fileToByteString(String filePath) { byte[] bytes = file2byte(filePath); return toHexString(bytes); } /** * 根据文件路径将文件转为二进制数组 * @param filePath:文件路径 * @return */ public static byte[] file2byte(String filePath) { byte[] buffer = null; try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); buffer = bos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; } /** * 将二进制数组转为字符串 * @param byteArray * @return */ private static String toHexString(byte[] byteArray) { if (byteArray == null || byteArray.length < 1) throw new IllegalArgumentException( "this byteArray must not be null or empty"); final StringBuilder hexString = new StringBuilder(); for (int i = 0; i < byteArray.length; i++) { if ((byteArray[i] & 0xff) < 0x10)// 0~F前面不零 hexString.append("0"); hexString.append(Integer.toHexString(0xFF & byteArray[i])); } return hexString.toString().toLowerCase(); } public String getInoutFilePath(Date date) { if (null == date) { date = new Date(); } String basePath = configData.getImgPath() + "INOUT/" + DateFormatUtils.format(date, "yyyyMM") + "/"; File file = new File(basePath); if (!file.exists()) { file.mkdirs(); } return basePath; } }