美文网首页
java 日常工具类

java 日常工具类

作者: 咖啡机an | 来源:发表于2019-01-11 11:03 被阅读0次

    目录
    1.文件上传处理
    2.从网络Url中下载文件
    3.将文件复制到Web的临时文件中
    4.判断坐标不为空
    5.获得图片的base64码
    6.将目标目录的文件压缩成Zip文件
    7.删除文件夹
    8.object对象list——>hashMapList
    具体方法的代码

     /**
         * 文件上传处理
         *
         * @param request
         * @param savePath
         * @param resType  资源类型 10:图片 20:文件
         * @return
         * @throws IOException
         */
        public static List<TResourcePo> uploadFileComb(HttpServletRequest request, String savePath,
                                                       int resType, Integer resSubType) throws IOException {
            //上传文件集合
            Map<String, MultipartFile> fileMap = null;
            //上传图片数据详情
            List<TResourcePo> geResDataList = null;
            MultipartFile mf = null;
            String fileName = null;
            File uploadFile = null;
            TResourcePo geResItem = null;
            if (request instanceof MultipartHttpServletRequest) {
                MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
                // 获取上传的文件
                fileMap = multipartHttpServletRequest.getFileMap();
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                geResDataList = new ArrayList<>();
                for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                    mf = entity.getValue();
                    fileName = mf.getOriginalFilename();
                    uploadFile = new File(savePath + fileName);
                    FileCopyUtils.copy(mf.getBytes(), uploadFile);
                    geResItem = new TResourcePo();
                    //资源名称
                    geResItem.setResName(fileName.substring(0, fileName.lastIndexOf(".")));
                    //资源类型
                    geResItem.setResType(resType);
                    geResItem.setResSubType(resSubType);
                    //资源文件格式
                    geResItem.setResFormat(fileName.substring(fileName.lastIndexOf(".") + 1));
                    //资源文件大小
                    geResItem.setResSize((int) mf.getSize());
                    //资源路径
                    geResItem.setResUrl(savePath);
                    //
                    geResDataList.add(geResItem);
                }
            }
            return geResDataList;
        }
    
    
    /**
         * 从网络Url中下载文件
         *
         * @param urlStr   文件路径 url+fileName+fileType   http://IP/tempImage/4K%20(2).jpg
         * @param fileName 下载到本地的名称 4.jpg
         * @param savePath 保存的路径
         * @throws IOException
         */
        public static boolean downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
            FileOutputStream fos = null;
            InputStream inputStream = null;
            URL url = new URL(urlStr);
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //设置超时间为3秒
                conn.setConnectTimeout(3 * 1000);
                //防止屏蔽程序抓取而返回403错误
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                //得到输入流
                inputStream = conn.getInputStream();
                //获取自己数组
                byte[] getData = readInputStream(inputStream);
                //文件保存位置
                File saveDir = new File(savePath);
                if (!saveDir.exists()) {
                    saveDir.mkdir();
                }
                File file = new File(saveDir + File.separator + fileName);
                fos = new FileOutputStream(file);
                fos.write(getData);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    fos.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            return true;
        }
     /**
         * 将文件复制到Web的临时文件中
         *
         * @param geResList
         * @param request
         */
        public static void getFileToWeb(HttpServletRequest request, List<TResourcePo> geResList) throws IOException {
            if (geResList != null && geResList.size() > 0) {
                //图片
                String strImagePath =
                        request.getServletContext().getRealPath("/").replace("rest", "web") + CommonConstant.IMAGE_TEMP_FOLDER;
                File fileImage = new File(strImagePath);
                if (!CommonMethod.isHasFolder(fileImage)) {
                    CommonMethod.createFolder(fileImage);
                }
                //附件
                String strFilePath =
                        request.getServletContext().getRealPath("/").replace("rest", "web") + CommonConstant.FILE_TEMP_FOLDER;
                File fileFile = new File(strFilePath);
                if (!CommonMethod.isHasFolder(fileFile)) {
                    CommonMethod.createFolder(fileFile);
                }
                int len = geResList.size();
                File fileFrom = null;
                File fileTo = null;
                TResourcePo item = null;
                for (int i = 0; i < len; i++) {
                    //文件下载的地址
                    String strPath = strImagePath;
                    String contextPath = CommonConstant.IMAGE_TEMP_FOLDER;
                    item = geResList.get(i);
                    if (item.getResType() == CommonConstant.RESOURCE_TYPE.FILE) {
                        strPath = strFilePath;
                        contextPath = CommonConstant.FILE_TEMP_FOLDER;
                    }
                    //文件下载路径
                    fileFrom = new File(item.getResUrl() + item.getResName() + "." + item.getResFormat());
                    if (fileFrom.exists()) {
                        if (!CommonMethod.hasFile(strPath + item.getResName() + "." + item.getResFormat())) {
                            fileTo = new File(strPath + item.getResName() + "." + item.getResFormat());
                            Files.copy(fileFrom.toPath(), fileTo.toPath());
                        }
                        item.setResUrl(request.getContextPath().replace("rest", "web") +
                                "/" + contextPath + item.getResName() + "." + item.getResFormat());
                    } else {
                        item.setResUrl(request.getContextPath().replace("rest", "web") +
                                "/" + contextPath);
                    }
                }
            }
        }
    /**
         * 判断坐标不为空
         *
         * @param coor 坐标 lng,lat
         * @return
         */
        public static boolean isNotEmptyCoor(String coor) {
            boolean result = false;
            String regex = "^0(.?0*)?$";
            String lng = coor.split(",")[0];
            String lat = coor.split(",")[1];
            if (!StringUtils.isEmpty(lng) && !lng.matches(regex)) {
                if (!StringUtils.isEmpty(lat) && !lat.matches(regex)) {
                    result = true;
                }
            }
            return result;
        }
    
    /**
         * 获得图片的base64码
         *
         * @param src
         * @return
         */
        public static String getImageBase(String src) {
            if (StringUtils.isEmpty(src)) {
                return "";
            }
            File file = new File(src);
            if (!file.exists()) {
                return "";
            }
            InputStream in = null;
            byte[] data = null;
            try {
                in = new FileInputStream(file);
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }
            try {
                data = new byte[in.available()];
                in.read(data);
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(data);
        }
    
        private static final int BUFFER = 8192;
    
        /**
         * 将目标目录的文件压缩成Zip文件
         *
         * @param srcPath 原文件名
         * @param dstPath 压缩文件名
         * @throws IOException
         */
        public static void compress(String srcPath, String dstPath) throws IOException {
            File srcFile = new File(srcPath);
            File dstFile = new File(dstPath);
            if (!srcFile.exists()) {
                throw new FileNotFoundException(srcPath + "不存在!");
            }
            FileOutputStream out = null;
            ZipOutputStream zipOut = null;
            try {
                out = new FileOutputStream(dstFile);
                CheckedOutputStream cos = new CheckedOutputStream(out, new CRC32());
                zipOut = new ZipOutputStream(cos);
                compress(srcFile, zipOut, "");
            } finally {
                if (null != zipOut) {
                    zipOut.close();
                    out = null;
                }
                if (null != out) {
                    out.close();
                }
            }
        }
    
        private static void compress(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
            if (file.isDirectory()) {
                compressDirectory(file, zipOut, baseDir);
            } else {
                compressFile(file, zipOut, baseDir);
            }
        }
    
        /**
         * 压缩一个目录
         */
        private static void compressDirectory(File dir, ZipOutputStream zipOut, String baseDir) throws IOException {
            File[] files = dir.listFiles();
            for (int i = 0; i < files.length; i++) {
                compress(files[i], zipOut, baseDir + dir.getName() + "/");
            }
        }
    
        /**
         * 压缩一个文件
         */
        private static void compressFile(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
            if (!file.exists()) {
                return;
            }
            BufferedInputStream bis = null;
            try {
                bis = new BufferedInputStream(new FileInputStream(file));
                ZipEntry entry = new ZipEntry(baseDir + file.getName());
                zipOut.putNextEntry(entry);
                int count;
                byte[] data = new byte[BUFFER];
                while ((count = bis.read(data, 0, BUFFER)) != -1) {
                    zipOut.write(data, 0, count);
                }
            } finally {
                if (null != bis) {
                    bis.close();
                }
            }
        }
    
        /**
         * 删除文件夹
         *
         * @param strFilePath
         */
        public static void deleteFileTempFloder(String strFilePath) {
            File baseFiles = new File(strFilePath);
            if (baseFiles.exists() && baseFiles.isDirectory()) {
                File[] files = baseFiles.listFiles();
                if (files != null && files.length > 0) {
                    for (File file : files) {
                        if (file.isFile()) {
                            file.delete();
                        } else if (file.isDirectory()) {
                            deleteFileTempFloder(file.getAbsolutePath());
                        }
                    }
                }
            }
            baseFiles.delete();
        }
    
        /**
         * 将Object对象里面的属性和值转化成Map对象
         *
         * @param obj
         * @param className
         * @return
         * @throws IllegalAccessException
         */
        public static HashMap<String, String> objectToMap(Object obj, Class<?> clazz) throws IllegalAccessException {
            HashMap<String, String> map = new HashMap<>(16);
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                String value = String.valueOf(field.get(obj));
                value = "null".equals(value) ? "" : value;
                map.put(fieldName, value);
            }
            return map;
        }
    
        public static List<HashMap<String, String>> listToMap(List<?> obj, Class<?> className) {
            List<HashMap<String, String>> mapList = new ArrayList<>();
            try {
                for (Object o : obj) {
                    mapList.add(objectToMap(o, className));
                }
            } catch (IllegalAccessException e) {
                logger.error("listToMap", e);
            }
            return mapList;
        }
    

    相关文章

      网友评论

          本文标题:java 日常工具类

          本文链接:https://www.haomeiwen.com/subject/uggtdqtx.html