java将网络资源url转换成File文件

        File file = null;
        InputStream inputStream = null;
        for (StockFileDTO stockFileDTO : fileList) {
            try {
                URL url = new URL(stockFileDTO.getUrl());
                String fileName = stockFileDTO.getFileName();
                URLConnection urlConnection = (URLConnection) url.openConnection();
                inputStream = urlConnection.getInputStream();
                file = File.createTempFile(fileName.substring(0,fileName.lastIndexOf(".")),fileName.substring(fileName.lastIndexOf(".") + 1));
                FileUtils.copyFile(inputStream, file);
                //将file文件对应业务使用
            } catch (IOException e) {
                log.error("文件转换失败e={}", e);
                throw new BusinessException("");
            } finally {
                try {
                    if (null != inputStream) {
                        inputStream.close();
                    }
                    // 用完删除
                    if (null != file) {
                        file.delete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

public class StockFileDTO {
    private String fileName;
    private String url;
}

// FileUtils
public class FileUtils {


    public static void checkAndMkdirsFilePath(String path) {
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
    }
    /**
     * 将文件读出来转化为字符串
     *
     * @param file
     *            源文件,不能是文件夹
     * @return
     */
    public static String loadFileToString(File file)
            throws FileNotFoundException, IOException {
        BufferedReader br = null;
        // 字符缓冲流,是个装饰流,提高文件读取速度
        br = new BufferedReader(new FileReader(file));
        String fileToString = buffReaderToString(br);
        br.close();
        return fileToString;
    }

    /**
     * 将文件读出来转化为字符串
     *
     * @param br
     *            源文件,不能是文件夹
     * @return
     * @throws IOException
     */
    public static String buffReaderToString(BufferedReader br)
            throws IOException {
        StringBuffer sb = new StringBuffer();
        String line = br.readLine();
        while (null != line) {
            sb.append(line);
            line = br.readLine();
        }
        return sb.toString();
    }

    /**
     * 流拷贝文件
     *
     * @param tempFile
     * @param newFile
     * @return
     * @throws IOException
     */
    public static long copyFile(File tempFile, File newFile) throws IOException {

        return copyFile(new FileInputStream(tempFile), newFile);
    }

    /**
     * 流拷贝文件
     *
     * @param is
     * @param newFile
     * @return
     * @throws IOException
     */
    public static long copyFile(InputStream is, File newFile)
            throws IOException {
        OutputStream os = new FileOutputStream(newFile);
        long s = IOUtils.copyLarge(is, os);
        os.flush();
        os.close();
        is.close();
        return s;
    }

    public static boolean createFile(File file) throws IOException{
        if(!file.exists()){
            file.createNewFile();
            return true;
        }else{
            return false;
        }
    }

    public static boolean deleteFile(File dir) {
        if (dir.exists()) {
            return dir.delete();
        } else {
            System.out.println("找不到要删除的文件:" + dir.getPath());
            return false;
        }
    }

    /**
     * 删除该目录下所有文件及文件夹
     *
     * @param dir
     * @return
     */
    public static void deleteDir(File... dir) {
        if (null != dir) {
            for (File file : dir) {
                if (null != file && file.isDirectory()) {
                    String[] children = file.list();
                    if(children == null) {
                        continue;
                    }
                    // 递归删除目录中的子目录下
                    for (int i = 0; i < children.length; i++) {
                        deleteDir(new File(file, children[i]));
                    }
                }
                // 目录此时为空,可以删除
                if(file != null)
                    file.delete();
            }

        }
    }

    public static void saveToFile(String fileName, InputStream in)
            throws IOException {
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = 0;
        bis = new BufferedInputStream(in);
        fos = new FileOutputStream(fileName);
        //
        while ((size = bis.read(buf)) != -1)
            fos.write(buf, 0, size);
        fos.close();
        bis.close();
    }

    public static boolean isPathFlagEnd(String path) {
        if(StringUtils.isBlank(path)) return false;
        return path.endsWith("/") || path.endsWith("\\");
    }

    public static boolean isPathFlagStart(String path) {
        if(StringUtils.isBlank(path)) return false;
        return path.startsWith("/") || path.startsWith("\\");
    }
    /**
     *
     * 拼接路径,目的是为了保持路径的完整性, 首尾不会验证
     * 如 splicePaths("root", "erji", "iii.jpg") == root/erji/iii.jpg
     * splicePaths("/root/", "/erji/", "/iii.jpg") == /root/erji/iii.jpg
     * @param path
     * @return
     */
    public static String splicePaths(String... path) {
        if (CollectionUtils.isEmpty(path)) {
            return "";
        }

        String separattor = "/";
        StringBuffer buffer = new StringBuffer();
        if(StringUtils.isNotBlank(path[0])) {
            buffer.append(path[0]);
        }

        for (int i = 1; i <= path.length - 1; i++) {
            String curr = path[i], pre = path[i - 1];
            if(StringUtils.isBlank(curr)) {
                continue;
            }
            boolean slefFlag = isPathFlagStart(curr);// 本身取 start
            boolean preFlag = isPathFlagEnd(pre);// 前一个取 end

            if (slefFlag && preFlag) {// 2个都有
                buffer.append(curr.substring(1, curr.length()));
            } else if (!slefFlag && !preFlag) {
                buffer.append(separattor).append(curr);
            } else {
                buffer.append(curr);
            }
        }
        return buffer.toString();
    }

    public static String getExtension(String pathName){
        if(StringUtils.isNotBlank(pathName) && pathName.contains(".")){
            return pathName.substring(pathName.lastIndexOf("."));
        }
        return pathName;
    }

    public static void main(String[] args) {
        //System.out.println(isPathFlagEnd("llll/"));
        //System.out.println(isPathFlagEnd("lll/l"));
        //System.out.println(isPathFlagStart("/lll/l"));

//		System.out.println(splicePaths("path", "ggg", "ffff.png"));
//		System.out.println(splicePaths("/path/", "/ggg/", "/ffff.png"));
//		System.out.println(splicePaths("/path/", "/ggg/", "/ffff.png/"));
//		System.out.println(splicePaths("/path/", "ggg", "/ffff.png"));
//		System.out.println(splicePaths("/path", "/ggg", "/ffff.png"));

        //String aa = "11231231.34324.jpg";
        //System.out.println(aa.substring(aa.lastIndexOf(".")));

        //System.out.println(splicePaths(null, "","lll", "", null, "ggg", "ffff.png"));
        String classPath = getClassPath();
        System.out.println(classPath);

        System.out.println(System.getProperty("os.name"));
    }

    public static String getClassPathLogoFilePath(){
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo/logo.png");
        // ClassPathResource classPathResource = new ClassPathResource("logo/logo.png");


        //ClassPathResource classPathResource = new ClassPathResource("logo/logo.png");

        //System.out.println(classPathResource.getPath());
        return url.getPath();


        //return s;
    }

    @Deprecated
    public static String getClassPath(){
        ClassPathResource classPathResource = new ClassPathResource("/logo/");
        //URL url = Thread.currentThread().getContextClassLoader().getResource("logo/");
        String _url = classPathResource.getPath();
        System.out.println(" ---- url :" + _url);
        //System.out.println("--- url:"+url.toString());
        int startSub = 4;
        if (System.getProperty("os.name").startsWith("W")){
            startSub = startSub + 1;
        }
        return  _url.substring(startSub,_url.length());
    }

   /* public static String getPaymentCode(){
        //ClassPathResource classPathResource = new ClassPathResource("logo/");
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo/qtj_payment_code.jpg");
        //String _url = classPathResource.getPath();
        // System.out.println(" ---- url :" + _url);
        System.out.println("--- url:"+url.toString());
        int startSub = 5;
        if (System.getProperty("os.name").startsWith("W")){
            startSub = startSub + 1;
        }
        return  url.toString().substring(startSub,url.toString().length());
    }

    public static String getDemoImg(){
        //ClassPathResource classPathResource = new ClassPathResource("logo/");
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo/demo.png");
        //String _url = classPathResource.getPath();
        // System.out.println(" ---- url :" + _url);
        System.out.println("--- url:"+url.toString());
        int startSub = 5;
        if (System.getProperty("os.name").startsWith("W")){
            startSub = startSub + 1;
        }
        return  url.toString().substring(startSub,url.toString().length());
    }

    public static String getInviteQRCodeImg(){
        //ClassPathResource classPathResource = new ClassPathResource("logo/");
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo/invite.jpg");
        //String _url = classPathResource.getPath();
        // System.out.println(" ---- url :" + _url);
        System.out.println("--- url:"+url.toString());
        int startSub = 5;
        if (System.getProperty("os.name").startsWith("W")){
            startSub = startSub + 1;
        }
        return  url.toString().substring(startSub,url.toString().length());
    }*/

    /**
     * 转换MultipartFile对象为java.io.File类型
     *
     * @param multipartFile
     * @return
     */
    public static File convertMultipartFileToFile(MultipartFile multipartFile) {
        File result = null;
        try {
            /**
             * UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法。
             * UUID(Universally Unique Identifier)全局唯一标识符,是指在一台机器上生成的数字,
             * 它保证对在同一时空中的所有机器都是唯一的,是由一个十六位的数字组成,表现出来的形式。
             * 由以下几部分的组合:当前日期和时间(UUID的第一个部分与时间有关,如果你在生成一个UUID之后,
             * 过几秒又生成一个UUID,则第一个部分不同,其余相同),时钟序列,
             * 全局唯一的IEEE机器识别号(如果有网卡,从网卡获得,没有网卡以其他方式获得),
             * UUID的唯一缺陷在于生成的结果串会比较长。
             *
             *
             * File.createTempFile和File.createNewFile()的区别:
             *  后者只是创建文件,而前者可以给文件名加前缀和后缀
             */
            //这里对生成的文件名加了UUID随机生成的前缀,后缀是null
            result = File.createTempFile(UUID.randomUUID().toString(), null);
            multipartFile.transferTo(result);
            result.deleteOnExit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    // 图片允许的后缀扩展名
    public static String[] IMAGE_FILE_EXTD = new String[] { "png", "bmp", "jpg", "jpeg","pdf" };

    public static boolean isFileAllowed(String fileName) {
        for (String ext : IMAGE_FILE_EXTD) {
            if (ext.equals(fileName)) {
                return true;
            }
        }
        return false;
    }

}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

水二大魔王

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

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

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

打赏作者

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

抵扣说明:

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

余额充值