jdk7 ftp下载功能:
public class Test
{
/**
*
* 本地文件名
*/
private String localfilename;
/**
*
* 远程文件名
*/
private String remotefilename;
/**
*
* FTP客户端
*/
private FtpClient ftpClient;
/**
* 服务器连接
*
* @param ip
* 服务器IP
* @param port
* 服务器端口
* @param user
* 用户名
* @param password
* 密码
* @param path
* 服务器路径
* @throws FtpProtocolException
*
*/
public void connectServer(String ip, int port, String user, String password, String path) throws FtpProtocolException
{
try
{
/* ******连接服务器的两种方法****** */
// 第一种方法
ftpClient =FtpClient.create();
ftpClient.connect(new InetSocketAddress(ip, port));
// 第二种方法
//ftpClient = FtpClient.create(ip);
//ftpClient.login(user, null, password);
ftpClient.login(user,password.toCharArray());
// 设置成2进制传输
ftpClient.setBinaryType();
System.out.println("login success!");
if (path.length() != 0)
{
// 把远程系统上的目录切换到参数path所指定的目录
ftpClient.changeDirectory(path);
}
ftpClient.setBinaryType();
} catch (IOException ex)
{
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/**
* 关闭连接
*
*/
public void closeConnect()
{
try
{
ftpClient.close();
System.out.println("disconnect success");
} catch (IOException ex)
{
System.out.println("not disconnect");
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/**
*
* 下载文件
*
* @param remoteFile
* 远程文件路径(服务器端)
* @param localFile
* 本地文件路径(客户端)
* @throws FtpProtocolException
*
*/
public void download(String remoteFile, String localFile) throws FtpProtocolException
{
TelnetInputStream is = null;
FileOutputStream os = null;
try
{
// 获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
is = (TelnetInputStream) ftpClient.getFileStream(remoteFile);
File file_in = new File(localFile);
os = new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1)
{
os.write(bytes, 0, c);
}
System.out.println("download success");
} catch (IOException ex)
{
System.out.println("not download");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally
{
try
{
if (is != null)
{
is.close();
}
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (os != null)
{
os.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}