import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FtpUtil {
public static FTPClient openFTP(String url, String username, String password) throws IOException
{
FTPClient ftp = new FTPClient();
ftp.setControlEncoding("gb2312");
ftp.connect(url);//连接FTP服务器 ,默认端口
//如采用端口,用ftp.connect(url,port)的方式直接连接FTP服务器
ftp.login(username, password);//登录
System.out.println("连接成功!");
return ftp;
}
public static void closeFTP(FTPClient ftp) throws IOException
{
ftp.disconnect();
System.out.println("关闭FTP!");
return ;
}
public static void newDir(FTPClient ftp, String path, String dir) throws IOException
{
ftp.changeWorkingDirectory(path);
ftp.makeDirectory(dir);
System.out.println("创建文件夹成功!");
return ;
}
public static void fileList(FTPClient ftp,String path) throws IOException
{
ftp.changeWorkingDirectory(path);
FTPFile[] file=ftp.listFiles(path);
for(int i=0;i<file.length;i++)
{
String tmp=file[i].getName();
if(file[i].getType()==1)
{
System.out.println("文件夹:"+tmp);
fileList(ftp, (path+ tmp+"/"));
}
else
{
System.out.println(file[i].getName()+"\t"+file[i].getType()+"\t"+file[i].getSize());
}
}
return ;
}
public static void uploadFile(FTPClient ftp,String path,String filename, FileInputStream input) throws IOException
{
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
return ;
}
public static void downloadFile(FTPClient ftp, String remotePath, String fileName, String localPath) throws IOException
{
ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs)
{
if (ff.getName().equals(fileName))
{
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
return ;
}
public static void main(String[] args) throws IOException
{
FTPClient ftp=openFTP("IP","name", "passwd"); //连接ftp
ftp.enterLocalPassiveMode(); // Use passive mode as default because most of us are behind firewalls these days.
ftp.setFileType(FTP.BINARY_FILE_TYPE); // 二进制文件支持!!!
newDir(ftp, "/test", "newDir"); // 在/test目录下创建文件夹
fileList(ftp, "/"); //列出目录下所有的文件
String fileName = "test.docx";
File uploadFile = new File("C:" + File.separator + fileName);
uploadFile(ftp, "/test/", "test.docx", new FileInputStream(uploadFile));
downloadFile(ftp, "/test", "test.docx", "D:\\");
closeFTP(ftp);
}
}
Java实现ftp操作~
最新推荐文章于 2021-05-06 15:39:48 发布