java下载文件(Java 下载文件的方法怎么写)

本文目录
- Java 下载文件的方法怎么写
- java FTP下载文件在代码中如何实现知道下载完成
- java文件下载为什么不能下载pdf
- 关于Java用输出流下载文件
- Java获取下载文件的大小
- 用java流的方式怎么指定下载到指定目录下
- JAVA 文件下载问题
- Java如何利用url下载MP3保存到本地
- JavaWeb下载文件,怎么获取文件下载完毕的状态
- java 下载异地FTP中的zip文件
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;
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;
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;
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;
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 FTP下载文件在代码中如何实现知道下载完成
public static void downloadFileFtp(KmConfig kmConfig,String fileName, String clientFileName, OutputStream outputStream){
try {
String ftpHost = kmConfig.getFtpHost();
int port = kmConfig.getFtpPort();
String userName = kmConfig.getFtpUser();
String passWord = kmConfig.getFtpPassword();
String path = kmConfig.getFtpPath();
FtpClient ftpClient = new FtpClient(ftpHost, port);// ftpHost为FTP服务器的IP地址,port为FTP服务器的登陆端口,ftpHost为String型,port为int型。
ftpClient.login(userName, passWord);// userName、passWord分别为FTP服务器的登陆用户名和密码
ftpClient.binary();
ftpClient.cd(path);// path为FTP服务器上保存上传文件的路径。
try {
TelnetInputStream in = ftpClient.get(fileName);
byte;
int cnt=0;
while ((cnt=in.read(bytes,0,bytes.length)) != -1) {
outputStream.write(bytes, 0, cnt);
}
//##############################################
//这里文件就已经下载完了,自己理解一下
//#############################################
outputStream.close();
in.close();
} catch (Exception e) {
ftpClient.closeServer();
e.printStackTrace();
}
ftpClient.closeServer();
} catch (Exception e) {
System.out.println("下载文件失败!请检查系统FTP设置,并确认FTP服务启动");
}
}
java文件下载为什么不能下载pdf
java文件下载不能下载pdf的原因:
1、电脑没装阅读器。
2、文件加密了。
3、对应的下载工具不支持。
4、Java类文件是Java程序的二进制表示形式。每一个类文件代表一个类或者接口。不可能在一个类文件中放入多个类或者接口。这样就使得无论类文件是在哪一种平台上生成,都可以在任何主机上执行。
关于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;
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获取下载文件的大小
可以直接通过HttpURLConnection 的getContentLength()方法来获取下载文件的大小。
//找到要下载的文件
***隐藏网址***
//根据响应获取文件大小
HttpURLConnection urlcon=(HttpURLConnection)url.openConnection();
//获取相应的文件长度
fileLength=urlcon.getContentLength();
备注:以上方法中url变换即可,下面的方法不用变更,即可获取到对应下载文件的大小。
用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 文件下载问题
如果是本地服务器的话,应该把文件发布,会生成一个url ,用这个url就可以下载了。
Java如何利用url下载MP3保存到本地
Java如何利用url下载MP3保存的方法:
1 /** ;
2 * TODO 下载文件到本地 ;
3 * @author nadim ;
4 * @date Sep 11, 2015 11:45:31 AM ;
5 * @param fileUrl 远程地址 ;
6 * @param fileLocal 本地路径 ;
7 * @throws Exception ;
8 */ ;
9 public void downloadFile(String fileUrl,String fileLocal) throws Exception {;
10 URL url = new URL(fileUrl);
11 HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
12 urlCon.setConnectTimeout(6000);
13 urlCon.setReadTimeout(6000);
14 int code = urlCon.getResponseCode();
15 if (code != HttpURLConnection.HTTP_OK) {
16 throw new Exception("文件读取失败");
17 }
18 //读文件流;
19 DataInputStream in = new DataInputStream(urlCon.getInputStream());
20 DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
21 byte;
22 int count = 0;
23 while ((count = in.read(buffer)) 》 0) {;
24 out.write(buffer, 0, count);
25 }
26 out.close();
27 in.close();
28 }。
Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征。
Java语言作为静态面向对象编程语言的代表,极好地实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程 。
JavaWeb下载文件,怎么获取文件下载完毕的状态
在Javaweb中,上传下载是经常用到的功能,对于文件上传,浏览器在上传的过程中是以流的过程将文件传给服务器,一般都是使用commons-fileupload这个包实现上传功能,因为commons-fileupload依赖于commons-io这个包,所以需要下载这两个包commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar。
1、搭建环境
创建Web项目,将包导入到项目lib下
2、实现文件上传
(第一种上传的方法)
新建upload.jsp页面
?
12345678910111213141516***隐藏网址***新建处理文件上传的Servlet
?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667***隐藏网址***(第二种上传的方法)
新建Jsp页面(同上,只是路径改变下)
?
12345678910111213141516***隐藏网址***建立Servlet处理上传
?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263***隐藏网址***(第三种上传的方法)
这里使用的是jspSmartUpload包上传下载,笔者认为这种上传下载较为简单,但是好像不是很多人用,不懂。
创建HTML页面
?
123456789101112131415161718192021222324252627***隐藏网址***创建Servlet处理上传文件
?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182***隐藏网址***注意:代码 int count = su.save("/share");表示你需要先建个文件夹,所以你可以先在Webcontent建立一个,然后将项目取消部署,再重新部署进去之后就会在运行那边建立起一个文件夹了!
或者你可以直接找到运行的路径,然后建立share文件夹。
3、实现文件下载
(第一种文件下载)
注意:该代码是直接访问Servlet类的
?
123456789101112131415161718192021222324252627282930313233343536373839404142***隐藏网址***(第二种下载方法)
新建jsp页面选择下载
《%@ page language="java" contentType="text/html; charset=UTF-8"
创建Servlet类进行下载(注意:该下载如果文件名是中文的话,一样会出现乱码现象)
package com.load;
(第三种下载的方法)
同上的jsp页面代码,这里就不再重复了。
新建Serlvet类,实现下载功能(注意:这里文件名就算是中文名,也不会出现乱码问题了!)
package com.load;
java 下载异地FTP中的zip文件
这个要做定时任务的,ftp不可能主动给你发,只能自己每隔多长时间就去检索一次,应该把ftp文件目录结构和文件名称全部存入数据库,在下载时候对文件的标识状态位进行更新,方便于对文件的判断。然后从ftp下载文件即可。如果需要连接ftp下载文件的代码,可以发送邮件到JavaWebDevelop@hotmial.com

更多文章:
手机百度一下百度(百度,手机百度,百度一下,三者有什么区别)
2026年9月7日 18:00
豆客平台人多还是175人多(资深玩家说豆客平台跟175pt哪个好)
2026年9月7日 11:30
安卓反编译apk(将原安卓apk反编译后签名,有原签名文件)
2026年9月7日 07:50






