/**
*参考例子如下:
*@paramnamelist下载的文件列表
*@parampath下载路径
*@paramzipname压缩文件名称
*/
publicvoidzipDownloadFile(HttpServletResponseresponse,List<string>namelist,Stringpath,Stringzipname){
byte[]buf=newbyte[1024];
try{
//本地保存设置
response.addHeader("Content-Disposition","attachment;filename="
+URLEncoder.encode(zipname,sysEncoding)+".zip");
response.setContentType("application/x-zip-compressed");
//向本地写文件
ServletOutputStreamsos=response.getOutputStream();
ZipOutputStreamzipOut=newZipOutputStream(newBufferedOutputStream(sos));
for(Stringname:namelist){
ZipEntryentry=newZipEntry(name);
zipOut.putNextEntry(entry);
InputStreambis=this.getStream(path,name);
if(bis!=null){
intreadLen=-1;
while((readLen=bis.read(buf,0,1024))!=-1){
zipOut.write(buf,0,readLen);
}
bis.close();
}
}
zipOut.close();
}catch(Exceptione){
e.printStackTrace();
}
}</string>
B. java如何实现txt下载 就是从远程FTP服务器上直接把TXT文本下载下来!
strUrl为文件地址,fileName为文件在本地的保存路径,试试吧~
public static void writeFile(String strUrl, String fileName) {
URL url = null;
try {
url = new URL(strUrl);
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e1) {
e1.printStackTrace();
}
OutputStream os = null;
try {
os = new FileOutputStream( fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
System.out.println("下载成功:"+strUrl);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
C. 怎样用java开发ftp客户端
package zn.ccfccb.util;
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;
import zn.ccfccb.util.CCFCCBUtil;
import zn.ccfccb.util.ZipUtilAll;
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);
// Log.info("连接远程上传服务器"+"192.168.54.106:"+2021);
// ftpClient.connect("192.168.54.106", 2021);
// ftpClient.login("hkrt-CCFCCBHK", "3OLJheziiKnkVcu7Sigz");
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);
}
}
}
}
// 调用样例:
public static void main(String[] args) {
try {
// 密钥/res/20150228
// ZipUtilAll.unZip(new File(("D:/123/123.zip")), "D:/123/");
// ZipDemo1232.unZip(new File(("D:/123/123.zip")), "D:/123/");
// 明文文件路径
String plainFilePath = "D:/req_20150204_0011.txt";
// 密文文件路径
String secretFilePath = "req_20150204_00134.txt";
// 加密
// encodeAESFile(key, plainFilePath, secretFilePath);
fileDownloadByFtp("D://123.zip","123.zip","req/20150228");
ZipUtilAll.unZip("D://123.zip", "D:/123/李筱/");
// 解密
plainFilePath = "D:/123.sql";
// secretFilePath = "D:/test11111.sql";
// decodeAESFile(key, plainFilePath, secretFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
D. java怎么打开FTP服务器上的文件
可以用文件流的方式直接写到服务器,也可以先在本地生成再调用ftp接口上传到服务器
E. 怎么用Java实现FTP上传
package com.sinosoft.sepmis.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
/**
* Java自带的API对FTP的操作
* @Title:Ftp.java
* @author: shanhong
*/
public class FtpUtil {
/**
* Description: 向FTP服务器上传文件
* @param url FTP服务器hostname
* @param port FTP服务器端口,如果默认端口请写-1
* @param username FTP登录账号
* @param password FTP登录密码
* @param path FTP服务器保存目录
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String url, int port, String username, String password, String path,
String filename, InputStream input) throws Exception
{
boolean success = false;
FTPClient ftp = new FTPClient();
try
{
int reply;
// 连接FTP服务器
if (port > -1)
{
ftp.connect(url, port);
}
else
{
ftp.connect(url);
}
// 登录FTP
ftp.login(username, password);
reply = ftp.getReplyCode();
System.out.println(reply);
if (!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
}
catch (IOException e)
{
success = false;
throw e;
}
finally
{
if (ftp.isConnected())
{
try
{
ftp.disconnect();
}
catch (IOException e)
{
throw e;
}
}
}
return success;
}
public static void main(String agrs[]) {
try {
File file = new File("E:\\1.txt");
FileInputStream in = new FileInputStream(file);
/*
* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器
*/
//返回true上传成功,否则上传失败
// FtpUtil.uploadFile("192.168.61.209", -22, "instiaci", "instiaci", "/db2home/instiaci/personal/shanhz","2.txt",in);
//“sinopipi/IC/tkk"目录要是已经存在的目录
FtpUtil.uploadFile("192.168.61.104", 22, "administrator", "123456", "/sinopipi/IC","6.txt",in);
} catch (Exception e) {
e.printStackTrace();
}
}
}
说明:所需的jar包是commons-net-2.0.jar
F. java ftp下载
这个和ftp没有太大关系,只是一个普通的下载,java连接ftp服务器传输文件是需要提供ip 端口号,用户名密码 路径的,这个只是一个静态资源,用这个就可以,支持断点续传
这边用到了apachecommons-httpclient-3.1包
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.RandomAccessFile;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.impl.client.DefaultHttpClient;
@SuppressWarnings("deprecation")
publicclassDownloadTool{
publicstaticvoidmain(String[]args)throwsClientProtocolException,IOException{
Stringurl="
[阳光电影
].神探驾到.BD.720p.国粤双语中字.mkv";
StringdownFile="d:\aaa.mkv";//本地存放路径
LongnetFileLenght=getNetFileSize(url);
LonglocalFileLenght=getLocalFileSize(downFile);
if(localFileLenght>=netFileLenght){
System.out.println("已下载完成");
return;
}
System.out.println("netFileLenght:"+netFileLenght+"localFileLenght:"+localFileLenght);
finalHttpClienthttpClient=newDefaultHttpClient();
httpClient.getParams().setIntParameter("http.socket.timeout",5000);
finalHttpGethttpGet=newHttpGet(url);
httpGet.addHeader("Range","bytes="+localFileLenght+"-");
finalHttpResponseresponse=httpClient.execute(httpGet);
finalintcode=response.getStatusLine().getStatusCode();
finalHttpEntityentity=response.getEntity();
System.out.println(code);
if(entity!=null&&code<400){
Filefile=newFile(downFile);
=newRandomAccessFile(file,"rw");
randomAccessFile.seek(localFileLenght);
InputStreaminputStream=entity.getContent();
intb=0;
finalbytebuffer[]=newbyte[1024];
while((b=inputStream.read(buffer))!=-1){
randomAccessFile.write(buffer,0,b);
}
randomAccessFile.close();
inputStream.close();
httpClient.getConnectionManager().shutdown();
System.out.println("下载完成");
}
}
(StringfileName){
Filefile=newFile(fileName);
returnfile.length();
}
(Stringurl){
Longcount=-1L;
finalHttpClienthttpClient=newDefaultHttpClient();
httpClient.getParams().setIntParameter("http.socket.timeout",5000);
finalHttpGethttpGet=newHttpGet(url);
HttpResponseresponse=null;
try{
response=httpClient.execute(httpGet);
finalintcode=response.getStatusLine().getStatusCode();
finalHttpEntityentity=response.getEntity();
if(entity!=null&&code==200){
count=entity.getContentLength();
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
httpClient.getConnectionManager().shutdown();
}
returncount;
}
}
G. java怎样读取http文件服务器上的文件列表并下载
要求文件名不能写死,那么只能到服务器上去遍历目录,如果服务器开了ftp权限的话到可以用apache的commons-net包,里面有ftp功能可以上传下载文件,也可以遍历文件