「java文件流下载文件」java通过流下载文件
本篇文章给大家谈谈java文件流下载文件,以及java通过流下载文件对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
- 1、用java实现文件的上传与下载
- 2、Java实现文件流下载文件,浏览器无反应,后台无错误!如何解决?
- 3、关于Java用输出流下载文件
- 4、用java流的方式怎么指定下载到指定目录下
- 5、Java 下载文件的方法怎么写
- 6、Java文件下载怎么实现的
用java实现文件的上传与下载
1.下载简单,无非是把服务器上的文件或者数据库中的BLob(或其他二进制型),用流读出来,然后写到客户端即可,要注意 ContentType。
2.上传,可以用Apache Commons Upload等开源工具,或者自己写:
form要用enctype="multipart/form-data"
然后服务器端也是用IO把客户端提交的文件流读入,然后写到服务器的文件系统或者数据库里。不同的数据库对Lob字段操作可能有所不同,建议用Hibernate,JPA等成熟的ORM框架,可以不考虑数据库细节。
Java实现文件流下载文件,浏览器无反应,后台无错误!如何解决?
//response.reset(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream");//APPLICATION/OCTET-STREAM response.addHeader("Content-Disposition", "attachment; filename=\""+fileName+"\""); //response.setContentLength((int)text.length()); byte[] b=new byte[100]; java.io.OutputStream os=null; java.io.InputStream is=null; try{ is=new java.io.ByteArrayInputStream(text.getBytes()); os=response.getOutputStream(); int len=0; while((len=is.read(b))0){ os.write(b,0,len); } response.setStatus( response.SC_OK ); //response.flushBuffer(); //os.flush(); //os.close(); is.close(); }catch(IOException e){ //response.reset(); e.printStackTrace(); } fileName的值是一个文件名,如:李四.csv 警告: Parameters: Invalid chunk ignored. Invalid chunk starting at byte [0] and ending at byte [0] with a value of [null] ignored 问题补充: //response.reset(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream");//APPLICATION/OCTET-STREAM response.addHeader("Content-Disposition", "attachment; filename=\""+fileName+"\""); //response.setContentLength((int)text.length()); byte[] b=new byte[100]; java.io.OutputStream os=null; java.io.InputStream is=null; try{ is=new java.io.ByteArrayInputStream(text.getBytes()); os=response.getOutputStream(); int len=0; while((len=is.read(b))0){ os.write(b,0,len); } response.setStatus( response.SC_OK ); //response.flushBuffer(); //os.flush(); //os.close(); is.close(); }catch(IOException e){ //response.reset(); e.printStackTrace(); } fileName的值是一个文件名,如:李四.csv 警告: Parameters: Invalid chunk ignored. Invalid chunk starting at byte [0] and ending at byte [0] with a value of [null] ignored 问题补充:大同小异啊,也没有看见关键性的差异。不同的地方我都试过了,还是无法解决! OpenMind 写道我有一段下载的代码,和你的有几个地方不一样,你自己看着修改一下吧: File file = new File(savePath + attachment.getPath()); /* 如果文件存在 */ if (file.exists()) { String disName = URLEncoder.encode( attachment.getDisplayName(), "UTF-8"); response.reset(); response.setContentType("application/x-msdownload"); response.addHeader("Content-Disposition", "attachment; filename=\"" + disName + "\""); int fileLength = (int) file.length(); response.setContentLength(fileLength); /* 如果文件长度大于0 */ if (fileLength != 0) { /* 创建输入流 */ InputStream inStream = new FileInputStream(file); byte[] buf = new byte[4096]; /* 创建输出流 */ ServletOutputStream servletOS = response .getOutputStream(); int readLength; while (((readLength = inStream.read(buf)) != -1)) { servletOS.write(buf, 0, readLength); } inStream.close(); servletOS.flush(); servletOS.close(); success = true; } } 问题补充:我已经把Log信息贴出来了,正在找问题,不知道有没有遇到过这个问题的! lifeidgp 写道1.response.setContentType("application/x-msdownload");加入这样代码试试; 3.用firebug抓包吧。 lifeidgp 写道1.response.setContentType("application/x-msdownload");加入这样代码试试; 3.用firebug抓包吧。
关于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流的方式怎么指定下载到指定目录下
举例代码:
/**
* 下载文件。
* @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 下载文件的方法怎么写
参考下面
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();
}
Java文件下载怎么实现的
下载就很简单了
把你要下载的文件做成超级链接,可以不用任何组件
比如说
下载一个word文档
a href="名称.doc"名称.doc/a
路径你自己写
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URL;
import java.util.Random;
/**
*
* 实现了下载的功能*/
public class SimpleTh {
public static void main(String[] args){
// TODO Auto-generated method stub
//String path = "倩女幽魂.mp3";//MP3下载的地址
String path ="";
try {
new SimpleTh().download(path, 3); //对象调用下载的方法
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getFilename(String path){//获得文件的名字
return path.substring(path.lastIndexOf('/')+1);
}
public void download(String path,int threadsize) throws Exception//下载的方法
{//参数 下载地址,线程数量
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();//获取HttpURLConnection对象
conn.setRequestMethod("GET");//设置请求格式,这里是GET格式
conn.setReadTimeout(5*1000);//
int filelength = conn.getContentLength();//获取要下载文件的长度
String filename = getFilename(path);
File saveFile = new File(filename);
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
accessFile.setLength(filelength);
accessFile.close();
int block = filelength%threadsize ==0?filelength/threadsize:filelength/threadsize+1;
for(int threadid = 0;threadid=threadsize;threadid++){
new DownloadThread(url,saveFile,block,threadid).start();
}
}
private final class DownloadThread extends Thread{
private URL url;
private File saveFile;
private int block;//每条线程下载的长度
private int threadid;//线程id
public DownloadThread(URL url,File saveFile,int block,int threadid){
this.url = url;
this.saveFile= saveFile;
this.block = block;
this.threadid = threadid;
}
@Override
public void run() {
//计算开始位置的公式:线程id*每条线程下载的数据长度=?
//计算结束位置的公式:(线程id+1)*每条线程下载数据长度-1=?
int startposition = threadid*block;
int endposition = (threadid+1)*block-1;
try {
try {
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
accessFile.seek(startposition);//设置从什么位置写入数据
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5*1000);
conn.setRequestProperty("Range","bytes= "+startposition+"-"+endposition);
InputStream inStream = conn.getInputStream();
byte[]buffer = new byte[1024];
int len = 0;
while((len = inStream.read(buffer))!=-1){
accessFile.write(buffer, 0, len);
}
inStream.close();
accessFile.close();
System.out.println("线程id:"+threadid+"下载完成");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
java文件流下载文件的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java通过流下载文件、java文件流下载文件的信息别忘了在本站进行查找喔。
发布于:2022-12-12,除非注明,否则均为
原创文章,转载请注明出处。