首先我們引入commons-net依賴,這是個基於Socket的ftp依賴,API在
http://commons.apache.org/proper/commons-net/apidocs/index.html
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.5</version>
</dependency>
登錄方式爲
//驗證登錄
try {
FTPClient ftp = new FTPClient();
ftp.connect(ip, port);
System.out.println(ftp.login(name, pwd));
ftp.setCharset(Charset.forName("UTF-8"));
ftp.setControlEncoding("UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
獲取文件列表方式:
FTPClient f = new FTPClient();
f.connect(server);
f.login(username, password);
FTPFile[] files = f.listFiles(directory);
FTPClient f = new FTPClient();
f.connect(server);
f.login(username,password);
FTPListParseEngine engine =
f.initiateListParsing("com.whatever.YourOwnParser", directory);
// FTPListParseEngine engine = f.initiateListParsing(directory);
while(engine.hasNext()){
FTPFile[] files = engine.getNext(25); // "page size" you want
//do whatever you want with these files, display them, etc.
//expensive FTPFile objects not created until needed.
}
上傳:
public void putFile(File file) {
try {
OutputStream os = ftp.storeFileStream(file.getName());
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int len = 0;
while ((len = fis.read(b)) != -1) {
os.write(b, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void putFiles(File srcFile) {
try {
if (!srcFile.exists()) {
srcFile.mkdirs();
}
for (File file : srcFile.listFiles()) {
if (file.isDirectory()) {
putFiles(file);
} else {
putFile(file);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
下載:
public void getFile(String fileName, File file) {
try {
//將ftp的file路徑下的"fileName"文件下載到本地目錄文件夾下面,並重命名爲"fileName"
ftp.retrieveFile(fileName, new FileOutputStream(new File(file.getPath() + "\\" + fileName)));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getFiles() {
List<String> fileNameList = getFilesName();
try {
ReadConfig readConfig = new ReadConfig();
DateUtil dateUtil = new DateUtil();
File toFile = new File(readConfig.getTempPath() + "\\" + dateUtil.getDay() + "12");
if (!toFile.exists()) {
toFile.mkdirs();
}
for (int i = 0; i < fileNameList.size(); i++) {
getFile(fileNameList.get(i), toFile);
System.out.println(fileNameList.get(i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
測試代碼:
// public static void main(String args[]) {
// FTPUtil ftpUtil = new FTPUtil("172.18.66.209",18200,"admin","1234-123");
// ftpUtil.getFilesName();
// ftpUtil.getFiles();
// File file = new File("D:\\thundersource\\2020051112");
// ftpUtil.putFiles(file);
// ftpUtil.putFile(file);
// //ftpUtil.putFile();
// ftpUtil.getFile();
// }
需要注意的是,當使用org.apache.commons.net.ftp.FTPClient通過協議SSH2進行SFTP連接時會報Could not parse response code.Server Reply: SSH-2.0-OpenSSH_5.3,原因是它不支持這種方式的連接(使用FTPSClient的SSL也是不行的)。,我們需要使用com.jcraft.jsch.JSch提供的SSH解決方法