java上传下载通用方法总结之FileUtils.copyInputStreamToFile(一)

java上传下载通用方法总结之FileUtils.copyInputStreamToFile(一)

java开发中上传下载,很多地方用。每次都去写的话会很麻烦。这里写一个通用方法,以后遇到了只要准备好对应参数,调方法即可。
这里引入的是

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.7</version>
        </dependency>
一、文件上传:
/**
 * 文件上传工具类
 */
public class FileUpload {
    /**
     * @param file     多媒体文件
     * @param filePath 文件上传到的目的路径
     * @param fileName 文件名称(不包括扩展名,即后缀)
     * @return
     */
    public static String fileUpload(MultipartFile file, String filePath, String fileName) throws IOException {
        //扩展名
        String exeName = "";

            if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
                exeName = file.getOriginalFilename().
                        substring(file.getOriginalFilename().lastIndexOf("."));
            }
            copyFile(file.getInputStream(), filePath, fileName + exeName);


        return fileName + exeName;
    }

    /**
     * @param inputStream 文件流
     * @param dir         目的文件夹
     * @param realName    文件全名
     * @return
     * @throws IOException
     */
    private static File copyFile(InputStream inputStream, String dir, String realName) throws IOException {

        File destFile = new File(dir, realName);
        return copyFile(inputStream, destFile);
    }

    private static File copyFile(InputStream inputStream, File destFile) throws IOException {
        if (null == inputStream) {
            return null;
        }
        if (!destFile.exists()) {
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdir();
            }
            destFile.createNewFile();
        }
        FileUtils.copyInputStreamToFile(inputStream, destFile);
        return destFile;
    }
 }

这里就是公共方法了。调用的时候,可以这样:(注意:这里的fileName只是纯名字,无后缀)

  @PostMapping("/upload")
    public R upload(@RequestBody MultipartFile file){

        String filePath="E:\\2020-in-beijing\\uploadanddownload";
        String fileName = "我的上传文件";
        String s = null;
        try {
            s = FileUpload.fileUpload(file, filePath, fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败!");
        }
        return R.ok("上传成功!").put("data",s);
    }
二 文件下载
package com.sinux.cc.fileuploadanddownload;

import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.print.DocFlavor;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 文件下载工具类
 */
public class FileDownload {
    /**
     * @param response
     * @param filePath 文件完整路径包括:文件完整名,扩展名
     */
    public static void fileDownLoad(HttpServletResponse response, String filePath) {
        OutputStream os = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return;
            }
            String fileName = file.getName();
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            //解决中文乱码
            String fileNameStr = new String(fileName.getBytes("utf-8"), "ISO8859-1");
            response.setHeader("Location", fileNameStr);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileNameStr);
            os = response.getOutputStream();
            download(os, filePath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static void download(OutputStream os, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
            int BUFFERSIZE = 2 << 10;
            int length = 0;
            byte[] buffer = new byte[BUFFERSIZE];
            while ((length = is.read(buffer, 0, BUFFERSIZE)) >= 0) {
                os.write(buffer, 0, length);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 浏览器下载
     */
    public static void download(InputStream in, String fileName) {
        HttpServletResponse res =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();


        try {
            res.reset();
            res.setCharacterEncoding("utf-8");
            res.setContentType("application/octet-stream");
            res.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[1024];
        BufferedInputStream bi = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bi = new BufferedInputStream(in);
            int i = bi.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, buffer.length);

                i = bi.read(buffer);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bi) {
                try {
                    bi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

这里提供了多种文件下载的方法:择其善者而用之

  • 4
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: `FileUtils.copyInputStreamToFile` 是一个 Java 类库中的方法,用于将输入流中的数据复制到目标文件中。 以下是该方法的签名: ```java public static void copyInputStreamToFile(InputStream source, File destination) throws IOException ``` 其中: - `source`:输入流,包含要复制到目标文件中的数据。 - `destination`:目标文件,即要将数据复制到其中的文件。 使用该方法可以很方便地将一个输入流中的数据复制到一个文件中。需要注意的是,在复制过程中,该方法会将输入流中的所有数据都复制到目标文件中,因此请确保目标文件足够大,以容纳输入流中的所有数据。 ### 回答2: 在Java编程中,我们经常需要将一个输入流中的数据复制到一个文件中。这时,我们可以使用FileUtils.copyInputStreamToFile方法来实现这个操作。下面,我将详细介绍这个方法的使用方法和注意事项。 FileUtils.copyInputStreamToFile方法的定义如下: public static void copyInputStreamToFile(InputStream source, File destination) throws IOException 该方法有两个参数,分别是输入流 source 和目标文件 destination。 使用该方法的步骤如下: 1. 首先,我们需要创建一个输入流对象,用于读取数据。例如,我们可以使用Java中的FileInputStream类来读取文件。 InputStream source = new FileInputStream("input.txt"); 2. 然后,我们需要创建一个目标文件对象,用于存储数据。例如,我们可以使用Java中的File类来表示文件。 File destination = new File("output.txt"); 3. 最后,我们调用FileUtils.copyInputStreamToFile方法将输入流中的数据复制到目标文件中。 FileUtils.copyInputStreamToFile(source, destination); 在使用FileUtils.copyInputStreamToFile方法时,我们需要注意以下几个方面: 1. 该方法会自动关闭输入流对象。因此,不需要我们手动关闭输入流。 2. 如果目标文件已经存在,该方法会覆盖目标文件中的内容。 3. 如果目标文件所在的目录不存在,该方法会自动创建目录。 4. 如果复制过程中出现异常,该方法会抛出IOException异常。因此,我们需要在调用该方法时进行异常处理。 总之,FileUtils.copyInputStreamToFile方法Java编程中常用的一个工具方法,可以将一个输入流中的数据复制到一个文件中。在使用该方法时,我们需要注意输入流的关闭、目标文件的覆盖和目录的创建等问题。 ### 回答3: fileutils.copyinputstreamtofile是一个Java中的文件操作工具,它提供了一种用于将输入流复制到文件的方法。 在Java中,输入流是从文件或其他数据源读取数据的流。FileUtils.copyInputStreamToFile()方法接受两个参数,第一个参数是输入流,第二个参数是目标文件。源文件的内容将被复制到目标文件中。 该方法的流程非常简单,它首先创建一个输出文件,并将输入流复制到这个输出文件中。当复制完成后,输入流将被关闭,并且输出文件将完成写入。 通常,文件复制操作涉及到的一些问题包括: 1.数据如何输入 2.如何控制写入的数据大小 3.如何处理可能发生的错误 FileUtils.copyInputStreamToFile()方法非常适合处理这些问题,并且提供了一种简单且可靠的方式来复制文件。 对于使用这种方法进行文件复制的程序,建议在方法执行之前进行一些必要的检查,例如防止复制不存在的文件或输入流为空等。 总之,fileutils.copyinputstreamtofile是一个非常方便的Java文件操作工具,可以帮助处理文件和数据的输入输出,以及文件复制等常见任务。使用这种方法可以简化代码,提高程序的可读性和可维护性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

神雕大侠mu

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

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

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

打赏作者

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

抵扣说明:

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

余额充值