由于项目需要用到对FTP上的文件进行上传下载等操作,先学习了一下。比较简单,下面来记录下步骤
一.先在另外机器上面安装一个FTP服务器,我选择的是SERV-U。这个比较好。先安装,然后设置FTP的IP,目录,用户名,密码,权限等,通过管理界面能很快速的进行配置OK
二.需要在工程的类路径上面加入一个JAR包ftp.jar
三.开始操作FTP上面的文件了
-
import
org.apache.commons.io.IOUtils;
-
import
org.apache.commons.net.ftp.FTPClient;
-
-
import
java.io.File;
-
import
java.io.FileInputStream;
-
import
java.io.IOException;
-
import
java.io.FileOutputStream;
-
-
-
-
-
-
public
class
FtpTest {
-
public
static
void
main(String[] args) {
-
testUpload();
-
-
}
-
-
-
-
-
public
static
void
testUpload() {
-
FTPClient ftpClient =
new
FTPClient();
-
FileInputStream fis =
null
;
-
-
try
{
-
ftpClient.connect(
"172.20.82.227"
);
-
ftpClient.login(
"oracle"
,
"oracle"
);
-
File srcFile =
new
File(
"E:/apache+tomcat.zip"
);
-
fis =
new
FileInputStream(srcFile);
-
-
ftpClient.changeWorkingDirectory(
"/home/oracle"
);
-
ftpClient.setBufferSize(
1024
);
-
ftpClient.setControlEncoding(
"GBK"
);
-
-
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
-
ftpClient.storeFile(
"apache+tomcat.zip"
, fis);
-
System.out.println(
"成功!"
);
-
}
catch
(IOException e) {
-
e.printStackTrace();
-
throw
new
RuntimeException(
"FTP客户端出错!"
, e);
-
}
finally
{
-
IOUtils.closeQuietly(fis);
-
try
{
-
ftpClient.disconnect();
-
}
catch
(IOException e) {
-
e.printStackTrace();
-
throw
new
RuntimeException(
"关闭FTP连接发生异常!"
, e);
-
}
-
}
-
}
-
-
-
-
-
public
static
void
testDownload() {
-
FTPClient ftpClient =
new
FTPClient();
-
FileOutputStream fos =
null
;
-
-
try
{
-
ftpClient.connect(
"192.168.14.117"
);
-
ftpClient.login(
"admin"
,
"123"
);
-
-
String remoteFileName =
"/admin/pic/3.gif"
;
-
fos =
new
FileOutputStream(
"c:/down.gif"
);
-
-
ftpClient.setBufferSize(
1024
);
-
-
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
-
ftpClient.retrieveFile(remoteFileName, fos);
-
}
catch
(IOException e) {
-
e.printStackTrace();
-
throw
new
RuntimeException(
"FTP客户端出错!"
, e);
-
}
finally
{
-
IOUtils.closeQuietly(fos);
-
try
{
-
ftpClient.disconnect();
-
}
catch
(IOException e) {
-
e.printStackTrace();
-
throw
new
RuntimeException(
"关闭FTP连接发生异常!"
, e);
-
}
-
}
-
}
-
-
}