⑴ java 在ftp上的所有文件查詢文件是否存在
packagetest;
importjava.io.DataInputStream;
importsun.net.ftp.FtpClient;
publicclassFtpDown1{
publicstaticvoidmain(Stringargs[])throwsException{
Stringhost="ip地址";
Stringpath="";
Stringusername="用戶名";
Stringpassword="密碼";
FtpClientclient=newFtpClient(host);
client.login(username,password);
client.binary();
client.cd("/目錄名稱");//如果是根目錄下直接寫個/就行了,或者不寫
DataInputStreamdis=newDataInputStream(client.nameList("test_*.xml"));
intreadCount;
Strings="";
while((s=dis.readLine())!=null){
//在此處判斷是否存在對應的文件
System.out.println("Getting:"+s);
}
}
}
⑵ java獲取ftp文件路徑怎麼寫
package com.weixin.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import com.weixin.constant.DownloadStatus;
import com.weixin.constant.UploadStatus;
/**
* 支持斷點續傳的FTP實用類
* @version 0.1 實現基本斷點上傳下載
* @version 0.2 實現上傳下載進度匯報
* @version 0.3 實現中文目錄創建及中文文件創建,添加對於中文的支持
*/
public class ContinueFTP {
public FTPClient ftpClient = new FTPClient();
public ContinueFTP(){
//設置將過程中使用到的命令輸出到控制台
this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
}
/**
* 連接到FTP伺服器
* @param hostname 主機名
* @param port 埠
* @param username 用戶名
* @param password 密碼
* @return 是否連接成功
* @throws IOException
*/
public boolean connect(String hostname,int port,String username,String password) throws IOException{
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding("GBK");
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username, password)){
return true;
}
}
disconnect();
return false;
}
/**
* 從FTP伺服器上下載文件,支持斷點續傳,上傳百分比匯報
* @param remote 遠程文件路徑
* @param local 本地文件路徑
* @return 上傳的狀態
* @throws IOException
*/
public DownloadStatus download(String remote,String local) throws IOException{
//設置被動模式
ftpClient.enterLocalPassiveMode();
//設置以二進制方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
DownloadStatus result;
//檢查遠程文件是否存在
FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes("GBK"),"iso-8859-1"));
if(files.length != 1){
System.out.println("遠程文件不存在");
return DownloadStatus.Remote_File_Noexist;
}
long lRemoteSize = files[0].getSize();
File f = new File(local);
//本地存在文件,進行斷點下載
if(f.exists()){
long localSize = f.length();
//判斷本地文件大小是否大於遠程文件大小
if(localSize >= lRemoteSize){
System.out.println("本地文件大於遠程文件,下載中止");
return DownloadStatus.Local_Bigger_Remote;
}
//進行斷點續傳,並記錄狀態
FileOutputStream out = new FileOutputStream(f,true);
ftpClient.setRestartOffset(localSize);
InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));
byte[] bytes = new byte[1024];
long step = lRemoteSize /100;
long process=localSize /step;
int c;
while((c = in.read(bytes))!= -1){
out.write(bytes,0,c);
localSize+=c;
long nowProcess = localSize /step;
if(nowProcess > process){
process = nowProcess;
if(process % 10 == 0)
System.out.println("下載進度:"+process);
//TODO 更新文件下載進度,值存放在process變數中
}
}
in.close();
out.close();
boolean isDo = ftpClient.completePendingCommand();
if(isDo){
result = DownloadStatus.Download_From_Break_Success;
}else {
result = DownloadStatus.Download_From_Break_Failed;
}
}else {
OutputStream out = new FileOutputStream(f);
InputStream in= ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));
byte[] bytes = new byte[1024];
long step = lRemoteSize /100;
long process=0;
long localSize = 0L;
int c;
while((c = in.read(bytes))!= -1){
out.write(bytes, 0, c);
localSize+=c;
long nowProcess = localSize /step;
if(nowProcess > process){
process = nowProcess;
if(process % 10 == 0)
System.out.println("下載進度:"+process);
//TODO 更新文件下載進度,值存放在process變數中
}
}
in.close();
out.close();
boolean upNewStatus = ftpClient.completePendingCommand();
if(upNewStatus){
result = DownloadStatus.Download_New_Success;
}else {
result = DownloadStatus.Download_New_Failed;
}
}
return result;
}
/**
* 上傳文件到FTP伺服器,支持斷點續傳
* @param local 本地文件名稱,絕對路徑
* @param remote 遠程文件路徑,使用/home/directory1/subdirectory/file.ext 按照Linux上的路徑指定方式,支持多級目錄嵌套,支持遞歸創建不存在的目錄結構
* @return 上傳結果
* @throws IOException
*/
public UploadStatus upload(String local,String remote) throws IOException{
//設置PassiveMode傳輸
ftpClient.enterLocalPassiveMode();
//設置以二進制流的方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("GBK");
UploadStatus result;
//對遠程目錄的處理
String remoteFileName = remote;
if(remote.contains("/")){
remoteFileName = remote.substring(remote.lastIndexOf("/")+1);
//創建伺服器遠程目錄結構,創建失敗直接返回
if(CreateDirecroty(remote, ftpClient)==UploadStatus.Create_Directory_Fail){
return UploadStatus.Create_Directory_Fail;
}
}
//檢查遠程是否存在文件
FTPFile[] files = ftpClient.listFiles(new String(remoteFileName.getBytes("GBK"),"iso-8859-1"));
if(files.length == 1){
long remoteSize = files[0].getSize();
File f = new File(local);
long localSize = f.length();
if(remoteSize==localSize){
return UploadStatus.File_Exits;
}else if(remoteSize > localSize){
return UploadStatus.Remote_Bigger_Local;
}
//嘗試移動文件內讀取指針,實現斷點續傳
result = uploadFile(remoteFileName, f, ftpClient, remoteSize);
//如果斷點續傳沒有成功,則刪除伺服器上文件,重新上傳
if(result == UploadStatus.Upload_From_Break_Failed){
if(!ftpClient.deleteFile(remoteFileName)){
return UploadStatus.Delete_Remote_Faild;
}
result = uploadFile(remoteFileName, f, ftpClient, 0);
}
}else {
result = uploadFile(remoteFileName, new File(local), ftpClient, 0);
}
return result;
}
/**
* 斷開與遠程伺服器的連接
* @throws IOException
*/
public void disconnect() throws IOException{
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}
/**
* 遞歸創建遠程伺服器目錄
* @param remote 遠程伺服器文件絕對路徑
* @param ftpClient FTPClient對象
* @return 目錄創建是否成功
* @throws IOException
*/
public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{
UploadStatus status = UploadStatus.Create_Directory_Success;
String directory = remote.substring(0,remote.lastIndexOf("/")+1);
if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"iso-8859-1"))){
//如果遠程目錄不存在,則遞歸創建遠程伺服器目錄
int start=0;
int end = 0;
if(directory.startsWith("/")){
start = 1;
}else{
start = 0;
}
end = directory.indexOf("/",start);
while(true){
String subDirectory = new String(remote.substring(start,end).getBytes("GBK"),"iso-8859-1");
if(!ftpClient.changeWorkingDirectory(subDirectory)){
if(ftpClient.makeDirectory(subDirectory)){
ftpClient.changeWorkingDirectory(subDirectory);
}else {
System.out.println("創建目錄失敗");
return UploadStatus.Create_Directory_Fail;
}
}
start = end + 1;
end = directory.indexOf("/",start);
//檢查所有目錄是否創建完畢
if(end <= start){
break;
}
}
}
return status;
}
/**
* 上傳文件到伺服器,新上傳和斷點續傳
* @param remoteFile 遠程文件名,在上傳之前已經將伺服器工作目錄做了改變
* @param localFile 本地文件File句柄,絕對路徑
* @param processStep 需要顯示的處理進度步進值
* @param ftpClient FTPClient引用
* @return
* @throws IOException
*/
public UploadStatus uploadFile(String remoteFile,File localFile,FTPClient ftpClient,long remoteSize) throws IOException{
UploadStatus status;
//顯示進度的上傳
long step = localFile.length() / 100;
long process = 0;
long localreadbytes = 0L;
RandomAccessFile raf = new RandomAccessFile(localFile,"r");
OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes("GBK"),"iso-8859-1"));
//斷點續傳
if(remoteSize>0){
ftpClient.setRestartOffset(remoteSize);
process = remoteSize /step;
raf.seek(remoteSize);
localreadbytes = remoteSize;
}
byte[] bytes = new byte[1024];
int c;
while((c = raf.read(bytes))!= -1){
out.write(bytes,0,c);
localreadbytes+=c;
if(localreadbytes / step != process){
process = localreadbytes / step;
System.out.println("上傳進度:" + process);
//TODO 匯報上傳狀態
}
}
out.flush();
raf.close();
out.close();
boolean result =ftpClient.completePendingCommand();
if(remoteSize > 0){
status = result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;
}else {
status = result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;
}
return status;
}
public static void main(String[] args) {
ContinueFTP myFtp = new ContinueFTP();
try {
System.err.println(myFtp.connect("10.10.6.236", 21, "5", "jieyan"));
// myFtp.ftpClient.makeDirectory(new String("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.changeWorkingDirectory(new String("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.makeDirectory(new String("愛你等於愛自己".getBytes("GBK"),"iso-8859-1"));
// System.out.println(myFtp.upload("E:\\yw.flv", "/yw.flv",5));
// System.out.println(myFtp.upload("E:\\愛你等於愛自己.mp4","/愛你等於愛自己.mp4"));
//System.out.println(myFtp.download("/愛你等於愛自己.mp4", "E:\\愛你等於愛自己.mp4"));
myFtp.disconnect();
} catch (IOException e) {
System.out.println("連接FTP出錯:"+e.getMessage());
}
}
}
⑶ java 怎麼判斷是否是文件夾就是從ftp讀入了一個目錄下的所有東西,然後要區分文件和文件夾。
File f;
f.isDirectory()
public boolean isDirectory()測試此抽象路徑名表示的文件是否是一個目錄。
返回:
當且僅當此抽象路徑名表示的文件存在且 是一個目錄時,才返回 true;否則返回 false
⑷ java向SFTP伺服器上傳文件,如何判斷伺服器上的文件夾是否存在
如果你的JAVA部署的tomcat,就是你要查找文件的伺服器,那就用:
File file = new File("文件路徑")。
如果你本地的JAVA想要訪問遠程的一個伺服器的文件是否存在,就得用如下方法:
URL url = new URL(「文件路徑:可以是本地伺服器的路徑,也可以是遠程伺服器的路徑」)
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
//message = urlcon.getHeaderField(0);
//文件存在『HTTP/1.1 200 OK』 文件不存在 『HTTP/1.1 404 Not Found』
Long TotalSize=Long.parseLong(urlcon.getHeaderField("Content-Length"));
if (TotalSize>0){
return true;
}else{
return false;
}
⑸ java在ftp上怎麼判斷文件是否存在不存在創建
其實用File對象挺容易的,自帶一個File.exists()方法,可以判斷file對象存不存在
⑹ java如何測試連接ftp是否通
java測試連接ftp是否連通可以使用判斷是否有異常來決定,實例如下:
/**
*connectServer
*連接ftp伺服器
*@throwsjava.io.IOException
*@parampath文件夾,空代表根目錄
*@parampassword密碼
*@paramuser登陸用戶
*@paramserver伺服器地址
*/
publicvoidconnectServer(Stringserver,Stringuser,Stringpassword,Stringpath)
throwsIOException
{
//server:FTP伺服器的IP地址;user:登錄FTP伺服器的用戶名
//password:登錄FTP伺服器的用戶名的口令;path:FTP伺服器上的路徑
ftpClient=newFtpClient();
ftpClient.openServer(server);
ftpClient.login(user,password);
//path是ftp服務下主目錄的子目錄
if(path.length()!=0)ftpClient.cd(path);
//用2進制上傳、下載
ftpClient.binary();
}
/**
*upload
*上傳文件
*@throwsjava.lang.Exception
*@return-1文件不存在
*-2文件內容為空
*>0成功上傳,返迴文件的大小
*@paramnewname上傳後的新文件名
*@paramfilename上傳的文件
*/
publiclongupload(Stringfilename,Stringnewname)throwsException
{
longresult=0;
TelnetOutputStreamos=null;
FileInputStreamis=null;
try{
java.io.Filefile_in=newjava.io.File(filename);
if(!file_in.exists())return-1;
if(file_in.length()==0)return-2;
os=ftpClient.put(newname);
result=file_in.length();
is=newFileInputStream(file_in);
byte[]bytes=newbyte[1024];
intc;
while((c=is.read(bytes))!=-1){
os.write(bytes,0,c);
}
}finally{
if(is!=null){
is.close();
}
if(os!=null){
os.close();
}
}
returnresult;
}
/**
*upload
*@throwsjava.lang.Exception
*@return
*@paramfilename
*/
publiclongupload(Stringfilename)
throwsException
{
Stringnewname="";
if(filename.indexOf("/")>-1)
{
newname=filename.substring(filename.lastIndexOf("/")+1);
}else
{
newname=filename;
}
returnupload(filename,newname);
}
/**
*download
*從ftp下載文件到本地
*@throwsjava.lang.Exception
*@return
*@paramnewfilename本地生成的文件名
*@paramfilename伺服器上的文件名
*/
publiclongdownload(Stringfilename,Stringnewfilename)
throwsException
{
longresult=0;
TelnetInputStreamis=null;
FileOutputStreamos=null;
try
{
is=ftpClient.get(filename);
java.io.Fileoutfile=newjava.io.File(newfilename);
os=newFileOutputStream(outfile);
byte[]bytes=newbyte[1024];
intc;
while((c=is.read(bytes))!=-1){
os.write(bytes,0,c);
result=result+c;
}
}catch(IOExceptione)
{
e.printStackTrace();
}
finally{
if(is!=null){
is.close();
}
if(os!=null){
os.close();
}
}
returnresult;
}
/**
*取得某個目錄下的所有文件列表
*
*/
publicListgetFileList(Stringpath)
{
Listlist=newArrayList();
try
{
DataInputStreamdis=newDataInputStream(ftpClient.nameList(path));
Stringfilename="";
while((filename=dis.readLine())!=null)
{
list.add(filename);
}
}catch(Exceptione)
{
e.printStackTrace();
}
returnlist;
}
/**
*closeServer
*斷開與ftp伺服器的鏈接
*@throwsjava.io.IOException
*/
publicvoidcloseServer()
throwsIOException
{
try
{
if(ftpClient!=null)
{
ftpClient.closeServer();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args)throwsException
{
FtpUtilftp=newFtpUtil();
try{
//連接ftp伺服器
ftp.connectServer("10.163.7.15","cxl","1","info2");
/**上傳文件到info2文件夾下*/
System.out.println("filesize:"+ftp.upload("f:/download/Install.exe")+"位元組");
/**取得info2文件夾下的所有文件列表,並下載到E盤下*/
Listlist=ftp.getFileList(".");
for(inti=0;i<list.size();i++)
{
Stringfilename=(String)list.get(i);
System.out.println(filename);
ftp.download(filename,"E:/"+filename);
}
}catch(Exceptione){
///
}finally
{
ftp.closeServer();
}
}
}
⑺ 用JAVA獲取FTP文件列表
學習一下ftp協議,然後用socket來模擬就可以了
⑻ ftp java 下載的時候怎麼保存到指定位置
通過工具類來實現本地路徑定義和下載即可。
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);
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 {
// 明文文件路徑
String plainFilePath = "D:/req_20150204_0011.txt";
// 密文文件路徑
String secretFilePath = "req_20150204_00134.txt";
fileDownloadByFtp("D://123.zip","123.zip","req/20150228");
} catch (Exception e) {
e.printStackTrace();
}
}
}
⑼ JAVA當中如何在FTP上查找文件或目錄是否存在
我覺得用file的exists就可以
File f=new File("file url");
if(f.exists()){
System.out.println("exists");
}
else{
System.out.println("not exist");
}