File 与 MultipartFile 相互转换;计算文件夹的最深层数;递归删除某个文件夹;File对象转为InputStream_multipartfile fileinputstream-程序员宅基地

技术标签: 工具类  java  学习笔记  

File --> InputStream

InputStream in = new FileInputStream(file);

 

MultipartFile对象 转换为 File 对象

/**
     * @Author: zcm
     * @DateTime: 2021/10/12 下午3:15
     * @Params: [org.springframework.web.multipart.MultipartFile]
     * @Return java.io.File
     * @Description: 将 MultipartFile对象 转换为 File 对象
     */
    public static File multipartFileToFile(MultipartFile file) throws IOException {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }
    /**
     * @Author: zcm
     * @DateTime: 2021/10/12 下午3:00
     * @Params: [java.io.InputStream, java.io.File]
     * @Return void
     * @Description: 获取流文件
     */
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 将File对象 转为 MultipartFile

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.LinkedList;
import java.util.Queue;

/**
     * @Author: zcm
     * @DateTime: 2021/10/12 下午3:01
     * @Params: [java.io.File]
     * @Return org.springframework.web.multipart.MultipartFile
     * @Description: 将File对象 转为 MultipartFile。
     * 转换出来后,注意对比一下,原生的MultipartFile 与 转换出来的 MultipartFile 的
     * 各个属性,因为计算文件幻数的时候,用的是MultipartFile。
     * MultipartFile不止一个实现类,File对象转MultipartFile时,注意看调试时 MultipartFile的实现类
     */
    public static MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = createFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    /**
     * @Author: zcm
     * @DateTime: 2021/10/12 下午3:12
     * @Params: [java.io.File]
     * @Return java.lang.String
     * @Description: 获取 MultipartFile 对象的 ContentType属性
     * 就是文件内容的类型
     */
    public static String getContentType(File file) {
        String s = null;
        try {
            s = Files.probeContentType(file.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * @Author: zcm
     * @DateTime: 2021/10/12 下午3:14
     * @Params: [java.io.File]
     * @Return org.apache.commons.fileupload.FileItem
     * @Description: 生成 new CommonsMultipartFile(fileItem) 的 FileItem
     */
    private static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(10240, null);
        String contentType = FileUtils.getContentType(file);
        FileItem item = factory.createItem("file", contentType, true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

计算文件夹最深层数

/**
     * @Author: zcm
     * @DateTime: 2021/10/11 下午8:09
     * @Params: [java.io.File, int]
     * @Return void
     * @Description: 计算文件夹的最大深度,如果超过 maximumOfFileTreeDepth 层,就抛出异常
     */
    private static int  maximumOfFileTreeDepth = 5;
    public static void checkFileTreeDepth(File file, int depth){
        File[] files = file.listFiles();
        for(int i = 0; i < files.length; i++){
            File f = files[i];
            if (f.isDirectory()){
                depth++;
                if (depth < FileUtils.maximumOfFileTreeDepth){
                    checkFileTreeDepth(f, depth);
                }else{
                    throw new RuntimeException("文件层数太深了!");
                }
                depth--;
            }
        }
        return ;
    }

递归删除某个文件夹

/**
     * @Author: zcm
     * @DateTime: 2021/10/11 下午8:14
     * @Params: [java.lang.String]
     * @Return void
     * @Description: 递归删除这个路径下的所有文件对象
     */
    public static void deleteAllFile(String path){
        File all = new File(path);		//获取其file对象
        File[] fs = all.listFiles();	//遍历path下的文件和目录,放在File数组中
        for(File f:fs){					//遍历File[]数组
            if(!f.isDirectory()){
                f.delete();
            }else {
                deleteAllFile(f.getAbsolutePath());
            }
        }
        all.delete();
    }

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_37905259/article/details/120739175

智能推荐

vue本地上传并预览php,vue.js 实现图片本地预览 裁剪 压缩 上传功能-程序员宅基地

文章浏览阅读130次。以下代码涉及 Vue 2.0 及 ES6 语法。目标纯 javascrpit 实现,兼容ie9及以上浏览器,在本地做好文件格式、长宽、大小的检测,减少浏览器交互。现实是残酷的,为了兼容Ie9 还是用上了 flash,第二篇来解释解释。代码结构点我上传图片 new Vue({el: '#wrap',data: {// 一张透明的图片src:'data:image/gif;base64,R0lGODl...

shell中的单引号和双引号理解_shell脚本双引号没了-程序员宅基地

文章浏览阅读5.4k次,点赞3次,收藏4次。问题描述: 最近在写shell脚本的时候,涉及到一个使用shell脚本发送json数据的问题,就是发送的json数据双引号不见了,导致数据格式不正确,收到了错误的响应。后来仔细查看了资料才发现自己之前对shell单引号和双引号的理解有一些问题,在此记录一些现象和结果。问题解析: 1.首先,我这边使用的..._shell脚本双引号没了

Python安全攻防-从入门到入狱-程序员宅基地

文章浏览阅读1.8w次,点赞43次,收藏246次。Python安全攻防-从入门到入狱_python安全攻防

混合云的容量扩展与功能添加-程序员宅基地

文章浏览阅读61次。1.使用混合云来增加数据中心容量“混合云”这个术语已经在IT操作团队中普遍使用,但并不是每个人对此都意见一致。基本上,混合云是指任何情况下,企业的部分应用程序在企业的数据中心运行,另一部分在一个公共云或多个公共云(如AWS,Microsoft Azure或Google云平台)中运行。同时,私有云是企业将云类型架构和功能并入自己的私有数据中心。这里的..._基于共有云快速扩展

网络——奈奎斯特定理和香农定理-程序员宅基地

文章浏览阅读7.7k次,点赞21次,收藏54次。在宽带受限且有噪声的信道中,为了不产生误差,信息的数据传输速率有上限值。那么,信道的极限数据传输速率就为:W∗log2(1+S/N)W*log_2(1+S/N)W∗log2​(1+S/N)其中,W 为带宽,单位是Hz,S/N 是信噪比(没有单位)注意:若题目中给出信噪比包含单位dB(分贝),则需要先进行转化例如,电话系统的典型参数是信道带宽为3000Hz,信噪比为30dB,则该系统的最大数据传输速率为多少?【分析】 由 10∗log10(S/N)=30dB10*log_10(S/N) = 30_奈奎斯特定理

flutter 旋转指定角度的动画组件_flutter 旋转角度-程序员宅基地

文章浏览阅读3.9k次。import 'package:flutter/material.dart';/// 旋转动画,旋转指定角度 动画 + Transform.rotate() 实现class RotateContainer extends StatefulWidget{ final double endAngle; // 旋转角度 final bool rotated; //是否旋转 ..._flutter 旋转角度

随便推点

关于sublime3的使用-程序员宅基地

文章浏览阅读40次。一、安装Package Control使用Ctrl+`快捷键或者通过View->Show Console菜单打开命令行,粘贴如下代码:importurllib.request,os; pf ='Package Control.sublime-package'; ipp =sublime.installed_packages_path(); urllib.request.inst...

uni-app 打包 ios 测试包,通过 testFlight 分发测试_uniapp testflight-程序员宅基地

文章浏览阅读5.2k次。uni-app 打包 ios 测试包,通过 testFlight 分发测试_uniapp testflight

php7 libevent扩展,php7下安装event扩展-程序员宅基地

文章浏览阅读66次。一·、安装支持库libevent,需要编译高版本(这里以最新版本release-2.1.8-stable为例)wget -c https://github.com/libevent/libevent/releases/download/release-2.1.8-stable/libevent-2.1.8-stable.tar.gz -P /usr/local/srccd /usr/local/s..._mac php7 pecl libevent

RabbitMQ:SpringBoot+RabbitMQ的简单实现之Topic模式_springboot rabbitmq 消费者如何写topic模式的-程序员宅基地

文章浏览阅读1.1k次。RabbitMQ:SpringBoot+RabbitMQ的简单实现之Topic模式1.在pom中添加springboot对amqp的支持&amp;lt;dependency&amp;gt; &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt; &amp;lt;artifactId&amp;gt;spring-boot-starter-amqp&a_springboot rabbitmq 消费者如何写topic模式的

微信小程序——使用excel-export导出excel_excel_export('a1:r18', 'store') excel_export('a20:-程序员宅基地

文章浏览阅读8.3k次,点赞3次,收藏41次。背景在学习微信小程序的过程中,需要导出excel文件数据,可是却没有后台服务器,所以只能够想着使用纯前端去导出excel 使用插件:excel-export导出思想将数据封装成excel文件 将excel文件上传到云存储中 将云存储的excel文件以图片的格式下载到本地 修改图片文件后缀为xlsx,成为excel文件操作将数据封装成excel文件;将excel文件上传到云存储中 建立云函数(我的云函数名称:uploadexportfile),打开云函数终端,安装excel-expo_excel_export('a1:r18', 'store') excel_export('a20:r34', 'agent')

element-ui中跑马灯的使用_elementplus走马灯获取当前-程序员宅基地

文章浏览阅读2.2w次,点赞10次,收藏13次。&lt;template&gt; &lt;div id="app"&gt; &lt;el-carousel :interval="5000" arrow="always"&gt; &lt;el-carousel-item v-for="(img,index) in imgList" :key="index"&gt; _elementplus走马灯获取当前