java流下载文件,java流写入文件

http://www.itjxue.com  2023-01-05 14:20  来源:未知  点击次数: 

用java流的方式怎么指定下载到指定目录下

举例代码:

????/**

?????*?下载文件。

?????*?@param?urlStr?文件的URL

?????*?@param?savePath?保存到的目录

?????*?@param?fileName?保存的文件名称

?????*?@param?description?描述(如:歌曲,专辑封面,歌词等)

?????*?@throws?IOException

?????*/

????public?static?void?downLoad(String?urlStr,?String?savePath,?String?fileName,?String?description)?throws?IOException

????{

????????URL?url?=?new?URL(urlStr);

????????HttpURLConnection?conn?=?(HttpURLConnection)?url.openConnection();

????????conn.setConnectTimeout(100000);??//?设置超时间为10秒

????????conn.setRequestProperty("User-Agent",?"Mozilla/4.0?(compatible;?MSIE?5.0;?Windows?NT;?DigExt)");??//?防止屏蔽程序抓取而返回403错误

????????File?saveDir?=?new?File(savePath);

????????File?file?=?new?File(saveDir?+?File.separator?+?fileName);

????????try?(InputStream?inputStream?=?conn.getInputStream();

????????????????FileOutputStream?fos?=?new?FileOutputStream(file))

????????{

????????????byte[]?flowData?=?readInputStream(inputStream);

????????????fos.write(flowData);

????????}?catch?(Exception?e)?{

????????????MainFrame.logEvent("字节保存时出现意外:"?+?e.getMessage());

????????}

????????MainFrame.logEvent(description?+?"下载完成:"?+?url);

????}

MainFrame.logEvent()是我自己弄的日志记录而已,可以忽略不看

Java用输出流下载文件的时候如何直接弹出(打开)保存对话框

你好,请看下这段程序

%

response.setCharacterEncoding("gb2312");

request.setCharacterEncoding("gb2312");

if (request.getParameter("file") != null) {

OutputStream os = null;

FileInputStream fis = null;

try {

String file = request.getParameter("file");

if (!(new File(file)).exists()) {

System.out.println("没有文件");

return;

}

System.out.println("文件名为:"+file);

os = response.getOutputStream();

response.setHeader("content-disposition", "attachment;filename=" + file);

response.setContentType("application/vnd.rn-realmedia-vbr");//此项内容随文件类型而异

byte temp[] = new byte[1000];

fis = new FileInputStream(file);

int n = 0;

while ((n = fis.read(temp)) != -1) {

os.write(temp, 0, n);

}

} catch (Exception e) {

out.print("出错");

} finally {

if (os != null)

os.close();

if (fis != null)

fis.close();

}

out.clear();

out = pageContext.pushBody();

}

%

form action="" method="post"

select name="file"

option value="C:\\Downloads\\冷山\\冷山.rmvb"

冷山

/option

/select

input type="submit"

/form

关于Java用输出流下载文件

通常可以直接通过FTPClient 工具类下载文件到本地的,可以通过ByteArrayOutputStream进行流的读取输出。

/**

*下载文件

*

* @param fileName

* @param date

* @param plainFilePath 明文文件路径路径

* @param filepath

* @return

* @throws Exception

*/

public static String encodeAESFileDownloadByFtp(String plainFilePath, String fileName, String date,String filepath) throws Exception {

FileInputStream fis = null;

ByteArrayOutputStream bos = null;

FileOutputStream fos = null;

FTPClient ftpClient = new FTPClient();

String bl = "false";

try {

// Log.info("下载并解密文件开始");

Log.info("连接远程下载服务器"+CMBCUtil.CMBCHOSTNAME+":"+2021);

ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);

ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);

FTPFile[] fs;

fs = ftpClient.listFiles();

for (FTPFile ff : fs) {

if (ff.getName().equals(filepath)) {

ftpClient.changeWorkingDirectory("/"+filepath+"/");

}

}

fs = ftpClient.listFiles();

for (FTPFile ff : fs) {

if (ff.getName().equals(date)) {

bl = "true";

ftpClient.changeWorkingDirectory("/"+filepath+"/" + date);

}

}

Log.info("检查文件路径是否存在:/"+filepath+"/"+date + " "+ bl);

if("false".equals(bl)){

ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath+"/" + date);

return bl;

}

bl = "false";

fs = ftpClient.listFiles();

for (FTPFile ff : fs) {

if (ff.getName().equals(fileName)) {

bl = "true";

Log.info("下载并解密文件开始。");

fos = new FileOutputStream(plainFilePath);

ftpClient.setBufferSize(1024);

// 设置文件类型(二进制)

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

InputStream is = ftpClient.retrieveFileStream(fileName);

bos = new ByteArrayOutputStream(is.available());

byte[] buffer = new byte[1024];

int count = 0;

while ((count = is.read(buffer)) != -1) {

bos.write(buffer, 0, count);

}

bos.flush();

byte[] bytes = decodeAES(key, bos.toByteArray());

fos = new FileOutputStream(plainFilePath);

fos.write(bytes);

Log.info("下载并解密文件结束:"+plainFilePath);

}

}

Log.info("检查文件是否存:"+fileName+" "+bl);

if("false".equals(bl)){

ViewUtil.dataSEErrorPerformedCommon("查询无结果,请稍后再查询。");

return bl;

}

return bl;

} catch (Exception e) {

throw e;

} finally {

if (fis != null) {

try {

fis.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

}

if (bos != null) {

try {

bos.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

}

if (fos != null) {

try {

fos.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

}

}

}

java 如何下载文件?

我用struts2给你实现:

1.首先struts2.xml 里面

action name="download" class="com.zfj.action.DownloadAction"

!-- 注意这里不再是返回一个字符串找到一个页面了

从服务器返回到本地客户端是一个流 我们需要配置流信息

type:表示接受方式或者跳转方法是

默认是 dispatcher 请求转发,所以之前我们一般不书写这个参数但是这里需要更改为stream重定向

--

result type="stream"

!--

因为之前我们设置的execute方法返回一个String,但是我们现在需要返回一个流。这里我们要指定一个新的方法为我们处理业务逻

辑并且返回流所以默认execute 方法对我们没有作用了,在这里我们指定一个新的方法为我们处理业务逻辑并且最后返回流

这里的inputName是固定写法 后面的名字dname要跟 action里面的getDname对应

--

param name="inputName"dname/param

!-- 当流返回过来时,我们应当设置头信息

给浏览器,这里设置的都是流信息

name里面的是固定写法

attachment:表示使用附件下载

online:直接打开

分号后的filename是固定写法,后面通过一个ognl表达式

引用下载的文件名

--

param name="contentDisposition"attachment;filename=${filename}/param

/result

/action

这里不再是返回一个字符串找到一个页面了。从服务器返回到本地客户端是一个流,我们需要配置流信息。

type:表示接受方式或者跳转方式是(默认是dispathcher请求转发,所以之前我们一般不书写这个,但是这里下载需要更改stream)

2.对应的DownloadAction

@Override

public String execute() throws Exception {

return this.SUCCESS;

}

//这里的getEtoak要跟struts.xml里的inputName的值对应

public InputStream getEtoak() throws Exception {

return new FileInputStream(

ServletActionContext.getServletContext()

.getRealPath("/image")

+ "/"

+ this.getFilename());

}

java 文件下载

这很奇怪啊,下载怎么会影响到Js脚本呢,看你的下载程序,这相当于一个完整的交互过程,如果要提出改进建议,我会说,你完全浪费 BufferedInputStream的优势,尤其是这句

byte[] buffer = new byte[fis.available()];

简直是败笔中的败笔,如果是个100m的文件,这要占多少内存?

建议这样使用:

byte[] buffer=new byte[4096];

int readByte=0;

while((readByte=fis.read(buffer)0){

toClient.write(buffer,0,readByte);

}

Java 下载文件的方法怎么写

参考下面

public HttpServletResponse download(String path, HttpServletResponse response) {

try {

// path是指欲下载的文件的路径。

File file = new File(path);

// 取得文件名。

String filename = file.getName();

// 取得文件的后缀名。

String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

// 以流的形式下载文件。

InputStream fis = new BufferedInputStream(new FileInputStream(path));

byte[] buffer = new byte[fis.available()];

fis.read(buffer);

fis.close();

// 清空response

response.reset();

// 设置response的Header

response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));

response.addHeader("Content-Length", "" + file.length());

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

response.setContentType("application/octet-stream");

toClient.write(buffer);

toClient.flush();

toClient.close();

} catch (IOException ex) {

ex.printStackTrace();

}

return response;

}

// 下载本地文件

public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {

String fileName = "Operator.doc".toString(); // 文件的默认保存名

// 读到流中

InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径

// 设置输出的格式

response.reset();

response.setContentType("bin");

response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

// 循环取出流中的数据

byte[] b = new byte[100];

int len;

try {

while ((len = inStream.read(b)) 0)

response.getOutputStream().write(b, 0, len);

inStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

// 下载网络文件

public void downloadNet(HttpServletResponse response) throws MalformedURLException {

int bytesum = 0;

int byteread = 0;

URL url = new URL("windine.blogdriver.com/logo.gif");

try {

URLConnection conn = url.openConnection();

InputStream inStream = conn.getInputStream();

FileOutputStream fs = new FileOutputStream("c:/abc.gif");

byte[] buffer = new byte[1204];

int length;

while ((byteread = inStream.read(buffer)) != -1) {

bytesum += byteread;

System.out.println(bytesum);

fs.write(buffer, 0, byteread);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

//支持在线打开文件的一种方式

public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {

File f = new File(filePath);

if (!f.exists()) {

response.sendError(404, "File not found!");

return;

}

BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));

byte[] buf = new byte[1024];

int len = 0;

response.reset(); // 非常重要

if (isOnLine) { // 在线打开方式

URL u = new URL("" + filePath);

response.setContentType(u.openConnection().getContentType());

response.setHeader("Content-Disposition", "inline; filename=" + f.getName());

// 文件名应该编码成UTF-8

} else { // 纯下载方式

response.setContentType("application/x-msdownload");

response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());

}

OutputStream out = response.getOutputStream();

while ((len = br.read(buf)) 0)

out.write(buf, 0, len);

br.close();

out.close();

}

(责任编辑:IT教学网)

更多

推荐计算机等级考试文章