1.需要上傳文件至FTP,需要的jar包
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.1</version> </dependency>
2.java代碼
@Test
public void test2(){
FTPClient ftp = new FTPClient();
try {
ftp.connect("1.1.1.1",21);//設置地址和端口號
ftp.login("aaa", "bbb");//用戶名和密碼
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);//上傳文件類型 二進制文件
int reply = ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){//檢查連接是否有效
System.out.println("error");
return;
}
ftp.changeWorkingDirectory("/test");
File file = new File("D:/jdbc.properties");
FileInputStream fis = new FileInputStream(file);
ftp.storeFile(file.getName(), fis);//關鍵代碼,把流持久化到硬盤上
fis.close();
ftp.logout();
ftp.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
其實總體來看就是兩個步驟,一個初始化FTPClient類,在來就是獲取流,然后寫到硬盤上.