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;

}

}

}

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Java文件操作类来保存文件到本地。具体步骤如下: 1. 创建一个 File 对象,表示要保存到的文件。例如: ```java File file = new File("C:\\data\\example.txt"); ``` 这里将保存文件到 C 盘的 data 目录下,并命名为 example.txt。 2. 创建一个 FileWriter 对象,用于向文件入数据。例如: ```java FileWriter writer = new FileWriter(file); ``` 3. 使用 FileWriter 的 write() 方法文件入数据。例如: ```java writer.write("Hello, world!"); ``` 4. 使用 FileWriter 的 flush() 方法将数据刷新到磁盘。例如: ```java writer.flush(); ``` 5. 关闭 FileWriter 对象,释放系统资源。例如: ```java writer.close(); ``` 完整示例代码如下: ```java import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileSaveExample { public static void main(String[] args) { File file = new File("C:\\data\\example.txt"); try { FileWriter writer = new FileWriter(file); writer.write("Hello, world!"); writer.flush(); writer.close(); System.out.println("File saved successfully."); } catch (IOException e) { System.out.println("An error occurred while saving the file."); e.printStackTrace(); } } } ``` 注意:在使用 FileWriter 时,如果指定的文件不存在,它会自动创建一个新文件。如果文件已经存在,则会覆盖原有的文件内容。如果你需要追加数据到已有的文件,可以使用 FileWriter 的另一个构造函数,并将第二个参数设为 true。例如: ```java FileWriter writer = new FileWriter(file, true); // 追加数据到已有的文件 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值