java实现文件保存到本地的方法

 更新时间:2017年02月03日 12:47:54   作者:园芳宝贝  
本篇文章主要介绍了java实现文件保存到本地的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

本篇介绍了java实现文件保存到本地的方法,具体代码如下:

private void savePic(InputStream inputStream, String fileName) {

    OutputStream os = null;
    try {
      String path = "D:\\testFile\\";
      // 2、保存到临时文件
      // 1K的数据缓冲
      byte[] bs = new byte[1024];
      // 读取到的数据长度
      int len;
      // 输出的文件流保存到本地文件

      File tempFile = new File(path);
      if (!tempFile.exists()) {
        tempFile.mkdirs();
      }
      os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
      // 开始读取
      while ((len = inputStream.read(bs)) != -1) {
        os.write(bs, 0, len);
      }

    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // 完毕,关闭所有链接
      try {
        os.close();
        inputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

文件保存方法.

附:

package com.ebways.web.upload.controller;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.ebways.web.base.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ebways.web.upload.url.UploadURL;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping(value = UploadURL.MODE_NAME)
public class UploadController extends BaseController {

  @RequestMapping(value = UploadURL.IMAGE_UPLOAD)
  @ResponseBody
  public String uploadFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IllegalArgumentException, Exception {
    // 参数列表
    Map<String, Object> map = new HashMap<>();
    map.put("file", file);
    savePic(file.getInputStream(), file.getOriginalFilename());

    //请求接口
    String apiReturnStr = "";//apiHttpRequest(map, API_HOST_URL + "/image/upload");

    return apiReturnStr;
  }

  private void savePic(InputStream inputStream, String fileName) {

    OutputStream os = null;
    try {
      String path = "D:\\testFile\\";
      // 2、保存到临时文件
      // 1K的数据缓冲
      byte[] bs = new byte[1024];
      // 读取到的数据长度
      int len;
      // 输出的文件流保存到本地文件

      File tempFile = new File(path);
      if (!tempFile.exists()) {
        tempFile.mkdirs();
      }
      os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
      // 开始读取
      while ((len = inputStream.read(bs)) != -1) {
        os.write(bs, 0, len);
      }

    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // 完毕,关闭所有链接
      try {
        os.close();
        inputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * <p class="detail">
   * 功能:公共Action
   * </p>
   *
   * @date 2016年9月8日
   * @author wangsheng
   */
  private String allowSuffix = "jpg,png,gif,jpeg";//允许文件格式
  private long allowSize = 2L;//允许文件大小
  private String fileName;
  private String[] fileNames;

  public String getAllowSuffix() {
    return allowSuffix;
  }

  public void setAllowSuffix(String allowSuffix) {
    this.allowSuffix = allowSuffix;
  }

  public long getAllowSize() {
    return allowSize * 1024 * 1024;
  }

  public void setAllowSize(long allowSize) {
    this.allowSize = allowSize;
  }

  public String getFileName() {
    return fileName;
  }

  public void setFileName(String fileName) {
    this.fileName = fileName;
  }

  public String[] getFileNames() {
    return fileNames;
  }

  public void setFileNames(String[] fileNames) {
    this.fileNames = fileNames;
  }


  /**
   * <p class="detail">
   * 功能:重新命名文件
   * </p>
   *
   * @return
   * @author wangsheng
   * @date 2016年9月8日
   */
  private String getFileNameNew() {
    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    return fmt.format(new Date());
  }

  /**
   * <p class="detail">
   * 功能:文件上传
   * </p>
   *
   * @param files
   * @param destDir
   * @throws Exception
   * @author wangsheng
   * @date 2014年9月25日
   */
  public void uploads(MultipartFile[] files, String destDir, HttpServletRequest request) throws Exception {
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
    try {
      fileNames = new String[files.length];
      int index = 0;
      for (MultipartFile file : files) {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        int length = getAllowSuffix().indexOf(suffix);
        if (length == -1) {
          throw new Exception("请上传允许格式的文件");
        }
        if (file.getSize() > getAllowSize()) {
          throw new Exception("您上传的文件大小已经超出范围");
        }
        String realPath = request.getSession().getServletContext().getRealPath("/");
        File destFile = new File(realPath + destDir);
        if (!destFile.exists()) {
          destFile.mkdirs();
        }
        String fileNameNew = getFileNameNew() + "." + suffix;//
        File f = new File(destFile.getAbsoluteFile() + "\\" + fileNameNew);
        file.transferTo(f);
        f.createNewFile();
        fileNames[index++] = basePath + destDir + fileNameNew;
      }
    } catch (Exception e) {
      throw e;
    }
  }

  /**
   *功能:文件上传
   *
   * @param file
   * @param destDir
   * @throws Exception
   * @author wangsheng
   * @date 2016年9月8日
   */
  public void upload(MultipartFile file, String destDir, HttpServletRequest request) throws Exception {
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
    try {
      String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
      int length = getAllowSuffix().indexOf(suffix);
      if (length == -1) {
        throw new Exception("请上传允许格式的文件");
      }
      if (file.getSize() > getAllowSize()) {
        throw new Exception("您上传的文件大小已经超出范围");
      }

      String realPath = request.getSession().getServletContext().getRealPath("/");
      File destFile = new File(realPath + destDir);
      if (!destFile.exists()) {
        destFile.mkdirs();
      }
      String fileNameNew = getFileNameNew() + "." + suffix;
      File f = new File(destFile.getAbsoluteFile() + "/" + fileNameNew);
      file.transferTo(f);
      f.createNewFile();
      fileName = basePath + destDir + fileNameNew;
    } catch (Exception e) {
      throw e;
    }
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 5分钟快速学会spring boot整合Mybatis的方法

    5分钟快速学会spring boot整合Mybatis的方法

    这篇文章主要给大家介绍了如何通过5分钟快速学会spring boot整合Mybatis的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用spring boot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-12-12
  • Spring Boot 之HelloWorld开发案例

    Spring Boot 之HelloWorld开发案例

    这篇文章主要介绍了Spring Boot 之HelloWorld开发案例,需要的朋友可以参考下
    2017-04-04
  • SpringBoot+Shiro学习之密码加密和登录失败次数限制示例

    SpringBoot+Shiro学习之密码加密和登录失败次数限制示例

    本篇文章主要介绍了SpringBoot+Shiro学习之密码加密和登录失败次数限制示例,可以限制登陆次数,有兴趣的同学可以了解一下。
    2017-03-03
  • Java中实现在一个方法中调用另一个方法

    Java中实现在一个方法中调用另一个方法

    下面小编就为大家分享一篇Java中实现在一个方法中调用另一个方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-02-02
  • Java中静态代理的使用与原理详解

    Java中静态代理的使用与原理详解

    这篇文章主要介绍了Java中静态代理的使用与原理详解,代理模式是为一个对象提供一个替身,以控制对这个对象的访问,即通过代理对象访问目标对象.这样做的好处是:可以在目标对象实现的基础上,增强额外的功能操作,即扩展目标对象的功能,需要的朋友可以参考下
    2023-09-09
  • java开发接口吞吐量提升10多倍技巧

    java开发接口吞吐量提升10多倍技巧

    这篇文章主要为大家介绍了java开发技巧之接口吞吐量提升10多倍的方法示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-01-01
  • Java中操作Word修订功能的示例详解

    Java中操作Word修订功能的示例详解

    Word的修订功能是一种在文档中进行编辑和审阅的功能,它允许多个用户对同一文档进行修改并跟踪这些修改,以便进行审查和接受或拒绝修改,下面我们就来学习一下Java中操作Word修订功能的方法,需要的可以参考下
    2023-12-12
  • SpringBoot项目获取统一前缀配置及获取非确定名称配置方法

    SpringBoot项目获取统一前缀配置及获取非确定名称配置方法

    在SpringBoot项目中,使用@ConfigurationProperties注解可获取统一前缀的配置,具体做法是创建配置类,使用prefix属性指定配置的前缀,本文给大家介绍SpringBoot项目获取统一前缀配置以及获取非确定名称配置方法,感兴趣的朋友跟随小编一起看看吧
    2024-09-09
  • Spring Boot Admin 快速入门详解

    Spring Boot Admin 快速入门详解

    这篇文章主要介绍了SpringBoot Admin 使用指南(推荐),Spring Boot Admin 是一个管理和监控你的 Spring Boot 应用程序的应用程序,非常具有实用价值,需要的朋友可以参考下
    2021-11-11
  • java虚拟机中多线程总结

    java虚拟机中多线程总结

    在本篇内容中小编给大家分享的是关于java虚拟机中多线程的知识点总结内容,需要的朋友们参考学习下。
    2019-06-06

最新评论