导航:首页 > 编程语言 > java流文件下载

java流文件下载

发布时间:2023-03-06 04:43:06

java 如何下载文件

httpURLConnection conn;
conn.getInputStream;
再将这个stream 写到文件就可以了

❷ 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 = "http://www.7cd.cn/QingTengPics/倩女幽魂.mp3";//MP3下载的地址
String path ="http://img.99luna.com/music/%CF%EB%C4%E3%BE%CD%D0%B4%D0%C5.mp3";

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流的方式怎么指定下载到指定目录下

举例代码:

/**
*下载文件。
*@paramurlStr文件的URL
*@paramsavePath保存到的目录
*@paramfileName保存的文件名称
*@paramdescription描述(如:歌曲,专辑封面,歌词等)
*@throwsIOException
*/
publicstaticvoiddownLoad(StringurlStr,StringsavePath,StringfileName,Stringdescription)throwsIOException
{
URLurl=newURL(urlStr);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(100000);//设置超时间为10秒
conn.setRequestProperty("User-Agent","Mozilla/4.0(compatible;MSIE5.0;WindowsNT;DigExt)");//防止屏蔽程序抓取而返回403错误

FilesaveDir=newFile(savePath);
Filefile=newFile(saveDir+File.separator+fileName);

try(InputStreaminputStream=conn.getInputStream();
FileOutputStreamfos=newFileOutputStream(file))
{
byte[]flowData=readInputStream(inputStream);
fos.write(flowData);
}catch(Exceptione){
MainFrame.logEvent("字节保存时出现意外:"+e.getMessage());
}
MainFrame.logEvent(description+"下载完成:"+url);
}

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

❹ 如何利用字节流实现java的文件上传下载

实现上传下载实际上就是io的转换。举例:
import hkrt.b2b.view.util.Log;
import hkrt.b2b.view.util.ViewUtil;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

public class CCFCCBFTP {

/**
* 上传文件
*
* @param fileName
* @param plainFilePath 明文文件路径路径
* @param filepath
* @return
* @throws Exception
*/
public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try {
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
Log.info("加密上传文件开始");
Log.info("连接远程上传服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(filepath)) {
bl="true";
ftpClient.changeWorkingDirectory("/"+filepath+"");
}
}
Log.info("检查文件路径是否存在:/"+filepath);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath);
return bl;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, fis);
Log.info("上传文件成功:"+fileName+"。文件保存路径:"+"/"+filepath+"/");
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);
}
}
}

}

/**
*下载文件
*
* @param localFilePath
* @param fileName
* @param routeFilepath
* @return
* @throws Exception
*/
public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FileOutputStream fos = null;
FTPClient ftpClient = new FTPClient();
String SFP = System.getProperty("file.separator");
String bl = "false";
try {
Log.info("下载并解密文件开始");
Log.info("连接远程下载服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
// ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);
// ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);
FTPFile[] fs;

ftpClient.makeDirectory(routeFilepath);
ftpClient.changeWorkingDirectory(routeFilepath);
bl = "false";
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
bl = "true";
Log.info("下载文件开始。");
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();
fos = new FileOutputStream(localFilePath+SFP+fileName);
fos.write(bos.toByteArray());
Log.info("下载文件结束:"+localFilePath);
}
}
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);
}
}
}
}}
备注:以上方法就实现了流的二进制上传下载转换,只需要将服务器连接部分调整为本地的实际ftp服务用户名和密码即可。

❺ Java 流文件 下载 用迅雷时 文件后缀 action

struts2的response不是servlet的response,是经过重定向的,如果你是用struts2的response来输出下载流,那迅雷肯定是读不到的。

❻ 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 下载文件的方法怎么写

参考下面
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("file:///" + 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流文件下载相关的资料

热点内容
cad安装卡在解压 浏览:615
编程精灵g540 浏览:256
手机文档解压之后解压包去哪儿了 浏览:923
java中网络编程重要吗 浏览:683
如何登录别人的服务器 浏览:626
调度系统软件python 浏览:205
微信大转盘抽奖源码 浏览:497
压缩机损坏的表现 浏览:862
同步数据服务器怎么用 浏览:634
163邮箱服务器的ip地址 浏览:50
服务器跟域是什么 浏览:128
rails启动命令 浏览:465
logistic命令怎么用 浏览:738
c语言点滴pdf 浏览:747
linuxrtc编程 浏览:258
linux打包并压缩命令 浏览:644
aes加密的证书格式 浏览:99
oracledbcalinux 浏览:844
酬勤任务app怎么被特邀 浏览:199
android应用文件夹 浏览:1002