本文目錄一覽:
- 1、java如何測試連接ftp是否通
- 2、java連接ftp是主動模式還是被動模式
- 3、JAVA編寫FTP連接報錯java.net.ConnectException: Connection refused: connect FTP
- 4、如何用java連接到ftp上
java如何測試連接ftp是否通
java測試連接ftp是否連通可以使用判斷是否有異常來決定,實例如下:
/**
* connectServer
* 連接ftp伺服器
* @throws java.io.IOException
* @param path 文件夾,空代表根目錄
* @param password 密碼
* @param user 登陸用戶
* @param server 伺服器地址
*/
public void connectServer(String server, String user, String password, String path)
throws IOException
{
// server:FTP伺服器的IP地址;user:登錄FTP伺服器的用戶名
// password:登錄FTP伺服器的用戶名的口令;path:FTP伺服器上的路徑
ftpClient = new FtpClient();
ftpClient.openServer(server);
ftpClient.login(user, password);
//path是ftp服務下主目錄的子目錄
if (path.length() != 0) ftpClient.cd(path);
//用2進位上傳、下載
ftpClient.binary();
}
/**
* upload
* 上傳文件
* @throws java.lang.Exception
* @return -1 文件不存在
* -2 文件內容為空
* 0 成功上傳,返迴文件的大小
* @param newname 上傳後的新文件名
* @param filename 上傳的文件
*/
public long upload(String filename,String newname) throws Exception
{
long result = 0;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
java.io.File file_in = new java.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 = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
return result;
}
/**
* upload
* @throws java.lang.Exception
* @return
* @param filename
*/
public long upload(String filename)
throws Exception
{
String newname = “”;
if (filename.indexOf(“/”)-1)
{
newname = filename.substring(filename.lastIndexOf(“/”)+1);
}else
{
newname = filename;
}
return upload(filename,newname);
}
/**
* download
* 從ftp下載文件到本地
* @throws java.lang.Exception
* @return
* @param newfilename 本地生成的文件名
* @param filename 伺服器上的文件名
*/
public long download(String filename,String newfilename)
throws Exception
{
long result = 0;
TelnetInputStream is = null;
FileOutputStream os = null;
try
{
is = ftpClient.get(filename);
java.io.File outfile = new java.io.File(newfilename);
os = new FileOutputStream(outfile);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
result = result + c;
}
} catch (IOException e)
{
e.printStackTrace();
}
finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
return result;
}
/**
* 取得某個目錄下的所有文件列表
*
*/
public List getFileList(String path)
{
List list = new ArrayList();
try
{
DataInputStream dis = new DataInputStream(ftpClient.nameList(path));
String filename = “”;
while((filename=dis.readLine())!=null)
{
list.add(filename);
}
} catch (Exception e)
{
e.printStackTrace();
}
return list;
}
/**
* closeServer
* 斷開與ftp伺服器的鏈接
* @throws java.io.IOException
*/
public void closeServer()
throws IOException
{
try
{
if (ftpClient != null)
{
ftpClient.closeServer();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String [] args) throws Exception
{
FtpUtil ftp = new FtpUtil();
try {
//連接ftp伺服器
(“10.163.7.15”, “cxl”, “1”, “info2”);
/** 上傳文件到 info2 文件夾下 */
System.out.println(“filesize:”+(“f:/download/Install.exe”)+”位元組”);
/** 取得info2文件夾下的所有文件列表,並下載到 E盤下 */
List list = (“.”);
for (int i=0;ilist.size();i++)
{
String filename = (String)list.get(i);
System.out.println(filename);
(filename,”E:/”+filename);
}
} catch (Exception e) {
///
}finally
{
;
}
}
}
java連接ftp是主動模式還是被動模式
正常情況下,默認使用主動模式 連接ftp;如果ftp仍然是登陸成功但是沒有上傳或下載文件,就在登陸後加入一行代碼,客戶端使用被動方式連接ftp服務端
ftpC.login(user, password);
// ftpC.enterLocalPassiveMode();
if (null != remotePath) {
// 打開進入指定目錄
ftpC.changeWorkingDirectory(remotePath);
}
JAVA編寫FTP連接報錯java.net.ConnectException: Connection refused: connect FTP
你用的FTPClient引入不對吧,我們項目上都是用的
import org.apache.commons.net.;
import org.apache.commons.net.;
import org.apache.commons.net.;
下面是我們項目上用到的FTP的實現代碼(FTP需要先連接,再登錄,之後就是校驗登錄是否成功),具體代碼如下:
/**
* 獲取FTPClient對象
*
* @param ftpHost FTP主機伺服器
* @param ftpPassword FTP 登錄密碼
* @param ftpUserName FTP登錄用戶名
* @param ftpPort FTP埠 默認為21
* @return FTPClient
* @throws Exception
*/
public static FTPClient getFTPClient(String ftpHost, String ftpUserName,
String ftpPassword, int ftpPort) throws Exception {
try {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftpHost, ftpPort);// 連接FTP伺服器
ftpClient.login(ftpUserName, ftpPassword);// 登陸FTP伺服器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
logger.error(“未連接到FTP,用戶名或密碼錯誤!”);
ftpClient.disconnect();
return null;
} else {
logger.info(“FTP連接成功!”);
return ftpClient;
}
} catch (SocketException socketException) {
logger.error(“FTP的IP地址可能錯誤,請正確配置!”);
throw socketException;
} catch (IOException ioException) {
logger.error(“FTP的埠錯誤,請正確配置!”);
throw ioException;
}
}
如何用java連接到ftp上
現在已經封裝好了的方法,不需要任何其他知識即可連接的。只需要知道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.;
import org.apache.commons.net.;
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);
}
原創文章,作者:PCLG,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/141778.html