java 文件保存_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 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();

}

}

}

/**

*

* 功能:公共Action

*

*

* @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;

}

/**

*

* 功能:重新命名文件

*

*

* @return

* @author wangsheng

* @date 2016年9月8日

*/

private String getFileNameNew() {

SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");

return fmt.format(new Date());

}

/**

*

* 功能:文件上传

*

*

* @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;

}

}

}

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

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的Java实现文件资源下载至本地的示例代码: ```java public void downloadFile(String url, String filePath) throws IOException { URL fileUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection(); connection.setRequestMethod("GET"); // 获取文件大小 int contentLength = connection.getContentLength(); // 创建文件输出流 FileOutputStream outputStream = new FileOutputStream(filePath); // 读取文件流并写入文件 InputStream inputStream = connection.getInputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; int totalBytesRead = 0; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); totalBytesRead += bytesRead; System.out.println(String.format("Downloaded %d/%d bytes", totalBytesRead, contentLength)); } // 关闭流 outputStream.close(); inputStream.close(); } ``` 在上面的代码中,我们通过 `URL` 类来创建一个文件资源的 URL 对象,并打开一个 `HttpURLConnection` 连接。然后,我们设置请求方法为 GET,并获取文件大小。接着,我们创建一个文件输出流,并通过 `InputStream` 类获取文件流。在读取文件流时,我们将每次读取的数据写入文件,并输出下载进度。最后,我们关闭流并结束下载。 你需要传入两个参数:文件资源的 URL 和本地文件保存的路径。例如,如果你要下载一个名为 `example.zip` 的文件,可以调用以下方法: ```java downloadFile("http://example.com/example.zip", "C:/Downloads/example.zip"); ``` 这将把文件下载到本地的 `C:/Downloads` 目录下。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值