开发者博客:[url]http://www.developsearch.com[/url]
/**
* 支持断点续传的FTP实用类
*
* @author chenxin
* @version [版本号, 2012-5-21]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class FtpUtils {
private FTPClient ftpClient = null;
private static final Logger logger = Logger.getLogger(FtpUtils.class);
private String hostname;
private String username;
private String password;
private int port;
private static final String EPUB_DIR = "epub_file";
public FtpUtils()
{
ftpClient = new FTPClient();
username = ServerConfig.get("ftp/ftp-user", "");
password = ServerConfig.get("ftp/ftp-password", "");
hostname = ServerConfig.get("ftp/ftp-host", "");
port = ServerConfig.getInt("ftp/ftp-port", 21);
// {
// //设置将过程中使用到的命令输出到控制台
// ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
// }
}
/**
* 连接到FTP服务器
* @param hostname 主机名
* @param port 端口
* @param username 用户名
* @param password 密码
* @return 是否连接成功
* @throws IOException
*/
public boolean connect() throws IOException{
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding(ServerConfig.get("ftp/ftp-charset", "GBK"));
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username, password)){
// 设置被动模式
ftpClient.enterLocalPassiveMode();
// 设置以二进制方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return true;
}
}
disconnect();
return false;
}
public boolean reconnect() throws IOException
{
disconnect();
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding(ServerConfig.get("ftp/ftp-charset", "GBK"));
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username, password)){
// 设置被动模式
ftpClient.enterLocalPassiveMode();
// 设置以二进制方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return true;
}
}
disconnect();
return false;
}
/**
* 从FTP服务器上下载文件,上传百分比
* @param remote
* @param dir
* @param fileName
* @return
* @throws IOException
* @see [类、类#方法、类#成员]
*/
public boolean download(String remote, String dir, String fileName)
throws IOException
{
File file = new File(dir + File.separator + fileName);
// 本地存在文件
if (file.exists())
{
if (logger.isDebugEnabled())
{
logger.debug("File is existsed.");
}
// 如果文件存在,但还未从FTP服务器上完全取下来,则需要等待
Long initialSize = 0L;
int i = 0;
while (initialSize != file.length())
{
i++;
initialSize = file.length();
try
{
Thread.sleep(100L);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (i > 1)
{
// 如果是刚下完的文件,则不需要再比对大小是否一致
return true;
}
}
Long localSize = file.length();
File localDir = new File(dir);
if (!localDir.exists())
{
localDir.mkdirs();
}
// 检查远程文件是否存在
if (remote.startsWith("/"))
{
remote = remote.substring(1);
}
if (ftpClient.listNames(remote).length <= 0)
{
// 文件不存在
logger.error("Could not find file from ftp server: " + remote);
return false;
}
// 计算远程文件大小
String s = "SIZE " + remote + "\r\n";
ftpClient.sendCommand(s);
String s1 = ftpClient.getReplyString();
Long remoteSize = Long.parseLong(s1.substring(3).trim());
if (logger.isDebugEnabled())
{
logger.debug("localsize: " + localSize + ", remoteSize: " + remoteSize);
}
if (remoteSize.equals(localSize))
{
if (logger.isDebugEnabled())
{
logger.debug("File's size not changed.");
}
return true;
}
else if (localSize != 0L)
{
if (logger.isDebugEnabled())
{
logger.debug("File's size changed which needed re-download.");
}
//远程文件和本地文件大小不一致,则删除本地文件
file.delete();
//如果是EPUB书路径,则需要把解压过的临时文件也一并删除
if (dir.indexOf(EPUB_DIR) > 0)
{
deleteAll(localDir);
}
}
// 重连以回到根目录
reconnect();
OutputStream out = new FileOutputStream(file);
InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("UTF-8"),
ServerConfig.get("ftp/ftp-charset", "GBK")));
if (logger.isDebugEnabled())
{
logger.debug("Begin to downloaded file from ftp.");
}
byte[] bytes = new byte[1024];
int count;
while ((count = in.read(bytes)) != -1)
{
out.write(bytes, 0, count);
}
if (logger.isDebugEnabled())
{
logger.debug("File has been downloaded from ftp successfully.");
}
in.close();
out.close();
boolean upNewStatus = ftpClient.completePendingCommand();
if (upNewStatus)
{
return true;
}
else
{
return false;
}
}
//递归删除文件夹
private void deleteAll(File file)
{
if (file.isDirectory() && !ArrayUtils.isEmpty(file.list()))
{
for (File childFile : file.listFiles())
{
deleteAll(childFile);
}
}
else
{
file.delete();
}
}
/** *//**
* 断开与远程服务器的连接
* @throws IOException
*/
public void disconnect() throws IOException{
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}
public static void main(String[] args) {
FtpUtils myFtp = new FtpUtils();
try {
myFtp.connect();
System.out.println(myFtp.download("/央视走西口/新浪网/走西口24.mp4", "E:\\走西口242.mp4", "123"));
myFtp.disconnect();
} catch (IOException e) {
System.out.println("连接FTP出错:"+e.getMessage());
}
}
//使用: 下载文件
FtpUtils ftpUtils = new FtpUtils();
ftpUtils.connect();
ftpUtils.download(fileUrl, directoryPath, filename);
ftpUtils.disconnect();
}