FTP    java.net.ConnectException: Connection refused: connect


排查问题如下: 一般是端口写错引起的 


(1):利用linux命令查看端口  netstat -auntp | grep 21


Last login: Fri Oct 28 12:12:24 2016 from 116.226.185.223 
[root@localhost ~]# netstat -auntp | grep 21 
tcp        0      0 0.0.0.0:2121                0.0.0.0:*                   LISTEN      20143/vsftpd         
tcp        0      0 :::3306                     :::*                        LISTEN      2184/mysqld          
tcp        0      0 ::ffff:127.0.0.1:3306       ::ffff:127.0.0.1:33699      ESTABLISHED 2184/mysqld          
tcp        0      0 ::ffff:127.0.0.1:3306       ::ffff:127.0.0.1:33700      ESTABLISHED 2184/mysqld          
tcp        0      0 ::ffff:127.0.0.1:3306       ::ffff:127.0.0.1:33661      ESTABLISHED 2184/mysqld          
tcp        0      0 ::ffff:127.0.0.1:3306       ::ffff:127.0.0.1:33688      ESTABLISHED 2184/mysqld          
tcp        0      0 ::ffff:127.0.0.1:3306       ::ffff:127.0.0.1:33625      ESTABLISHED 2184/mysqld          
tcp        0      0 ::ffff:127.0.0.1:3306       ::ffff:127.0.0.1:33687      ESTABLISHED 2184/mysqld          
tcp        0      0 ::ffff:127.0.0.1:3306       ::ffff:127.0.0.1:33702      ESTABLISHED 2184/mysqld          
[root@localhost ~]# 


(2): 如果连接后  读取数据为空 则  做如下修改:


ftp.enterLocalPassiveMode();//如果不加这个读取数据会为空 
FTPFile[] fs = ftp.listFiles();



(3):完整代码如下:


public  void ReadFileFromSftp() { 
 		 
	String path="uploads//"; 
	String fileName="20161012buy.txt"; 
 		String result=""; 
 		FTPClient ftp = new FTPClient(); 
 		 
 		try { 
 			int reply; 
 			//1.连接服务器 
 			ftp.connect(server,2121); 
 			//2.登录服务器 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 
 			ftp.login(user, password); 
 			//3.判断登陆是否成功 
 			reply = ftp.getReplyCode(); 
 			if (!FTPReply.isPositiveCompletion(reply)) { 
 				ftp.disconnect(); 
 			} 
 			//4.指定要下载的目录 
 			ftp.changeWorkingDirectory(path);// 转移到FTP服务器目录 
 			//5.遍历下载的目录 
 			ftp.enterLocalPassiveMode(); 
 			FTPFile[] fs = ftp.listFiles(); 
 			for (FTPFile ff : fs) { 
 				//解决中文乱码问题,两次解码 
 				byte[] bytes=ff.getName().getBytes("iso-8859-1"); 
 				String fn=new String(bytes,"utf8"); 
 				if (fn.equals(fileName)) { 
 					InputStream  inputStream=ftp.retrieveFileStream(ff.getName()); 
 					result = IOUtils.toString(inputStream); 
 				} 
 				 
 			} 
 			ftp.logout(); 
 		} catch (IOException e) { 
 			e.printStackTrace(); 
 		} finally { 
 			if (ftp.isConnected()) { 
 				try { 
 					ftp.disconnect(); 
 				} catch (IOException ioe) { 
 				} 
 			} 
 		} 
 		 
 		System.out.println("result"+result); 
 		 
 	} 
}



评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!