国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java實現文件保存到本地的方法

2019-11-26 13:09:35
字體:
來源:轉載
供稿:網友

本篇介紹了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() + "http://" + 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;    }  }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 太仓市| 襄樊市| 黎城县| 错那县| 罗田县| 资中县| 鲜城| 筠连县| 黎平县| 江陵县| 台南县| 新丰县| 德江县| 尼木县| 彝良县| 蓝田县| 永川市| 宣武区| 长岭县| 耿马| 城固县| 安康市| 信宜市| 中卫市| 榆林市| 济宁市| 沾益县| 佳木斯市| 麦盖提县| 新野县| 赫章县| 子长县| 南皮县| 彭泽县| 南召县| 台州市| 穆棱市| 东乡族自治县| 黑河市| 上犹县| 庄浪县|