项目引入依赖,maven需要导入的jar包
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>2.2</version>
<scope>compile</scope>
</dependency>
你可以检查的最后答复代码和文本用 getReplyCode , getReplyString 和 getReplyStrings。
通过定期向服务器发送NOOP命令,可以在客户端空闲时避免服务器断开连接。
ftp常用的三个方法
retrieveFile(String, OutputStream) 从ftp下载文件到本地目录下
appendFile(String, InputStream) 从ftp下载文件到本地目录
storeFile(String, InputStream) 从本地目录上传文件到ftp
/**
* 文件上传
* @param fileName 文件名称
* @param inputStream 输入流
* @param remotePath 文件上传路径
* @return
*/
public boolean uploadFile(String fileName, InputStream inputStream, String remotePath){
boolean isSeccess = false;
FTPClient ftpClient = null;
try {
//获取ftpClient客户端链接
ftpClient = ftpClientPool.borrowObject();
//创建remotePath目录,注意这个目录是只能创建单层文件夹,不能创建多层文件夹
//例如 文件目录是 /home/ibonc/template 只能创建/home/ibonc/template/previews 不能是 /home/ibonc/template/previews/201903
//还有这个目录是从/开始的,注意
ftpClient.makeDirectory(remotePath);
//切换工作目录,进入到创建文件夹目录
boolean flag = ftpClient.changeWorkingDirectory(remotePath);
if(flag){
//进入
//java中,内网用被动模式 ,外网连接时用主动模式,服务器相应改动(只用上线功能用被动模式去连接ftp报错连接不上)
//FTPClient ftpClient = new FTPClient();
//ftpClient.connect(url, port);
//ftpClient.enterLocalActiveMode(); //主动模式
//ftpClient.enterLocalPassiveMode(); 被动模式
ftpClient.enterLocalActiveMode();
//存储文件到ftp,input是输入流,fileName是文件名,转换编码存储
isSeccess = ftpClient.storeFile(new String(fileName.getBytes("UTF-8"), "ISO-8859-1"),inputStream);
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally{
ftpClientPool.returnObject(ftpClient);
}
return isSeccess;
}
/**
* 如果FTP器配置Nginx,可通过URL路径直接下载文件
* @param url 文件访问路径
* @param realName 文件名称
* @param request
* @param response
* @throws IOException
*/
public void fileDownNg(String url, String realName, HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedInputStream dis = null;
BufferedOutputStream fos = null;
try {
//获取服务器上的文件名 这里是格外注意的地方,下载不成功,要不就是文件名对不上,要不就是路径不对
String strName = url.substring(url.lastIndexOf("/") + 1);
//将url和编码之后的文件名拼接到一起,就是这个路径,在浏览器不需要这样,但是在编程中需要编码不然中文名文件,下载会有错误
url = url.substring(0,url.lastIndexOf("/"))+"/"+URLEncoder.encode(strName,"utf-8");
URL httpUrl = new URL(url);
//在浏览器中显示的名字编码。我们取的是utf-8的编码,浏览器用的是ISO-8859-1的编码
response.setHeader("Content-disposition", "attachment; filename=" + new String(realName.getBytes("UTF-8"), "ISO-8859-1"));
response.setHeader("Content-Length", String.valueOf(httpUrl.openConnection().getContentLength()));
//打开连接
dis = new BufferedInputStream(httpUrl.openStream());
//获取输出流
fos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[1024];
int bytesRead;
while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {
fos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dis != null)
dis.close();
if (fos != null)
fos.close();
}
}
/**
* 从FTP服务器下载文件到本地服务器
* @param remotePath ftp服务器文件目录
* @param realName 文件名称
* @param request
* @param response
* @return
*/
public boolean ftpDownFile(String remotePath, String realName, HttpServletRequest request, HttpServletResponse response) {
FTPClient ftpClient = null;
String fileName = null;
String localPath = null;
boolean isDownFile = false;
try {
int area = remotePath.lastIndexOf("/") + 1;
String remote = remotePath.substring(0, area);
fileName = remotePath.substring(area, remotePath.length());
ftpClient = ftpClientPool.borrowObject();
ftpClient.changeWorkingDirectory(remote);
URL url = Thread.currentThread().getContextClassLoader().getResource("/");
localPath = url.getPath();
File localFile = new File(localPath+fileName);
OutputStream is = new FileOutputStream(localFile);
//从服务器检索命名文件并将其写入给定的OutputStream。此方法不会关闭给定的OutputStream。如果当前文件类型为ASCII,
// 则文件中的行分隔符将转换为本地表示形式。如果成功完成则为True,否则为false。api解释
isDownFile = ftpClient.retrieveFile(new String(fileName.getBytes("UTF-8"),"ISO-8859-1"), is);
is.flush();
is.close();
//从工程目录下载到本地
fileDown(localPath+fileName, realName, request, response);
} catch (Exception e) {
e.printStackTrace();
}finally{
ftpClientPool.returnObject(ftpClient);
if(localPath!=null && fileName!=null){
File myFile = new File(localPath+fileName);
if(myFile.exists()){
myFile.delete();
}
}
}
return isDownFile;
}
/**
* 本地服务器下载文件到客户端
* @param filePath 文件路径
* @param realName 文件名称
* @param request
* @param response
* @throws IOException
*/
private void fileDown(String filePath, String realName, HttpServletRequest request, HttpServletResponse response) throws IOException {
FileInputStream fin = null;
ServletOutputStream out = null;
try{
response.setContentType("text/plain; charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setBufferSize(100 * 1024);
String fileType = filePath.substring(filePath.lastIndexOf(".") + 1);
String realfilename = realName + "." + fileType;
realfilename = URLDecoder.decode(realfilename, "utf-8");
realfilename = java.net.URLEncoder.encode(realfilename, "utf-8");
if(request.getHeader("User-Agent").indexOf("MSIE 5.5") != -1) {
response.setHeader("Content-Disposition", "filename=\"" + realfilename + "\"");
}else{
response.setHeader("Content-Disposition", "attachment; filename=\"" + new String((realfilename).getBytes(), "UTF-8") + "\"");
}
int len;
byte[] b = new byte[1024];
fin = new FileInputStream(filePath);
out = response.getOutputStream();
while((len = fin.read(b, 0, 1024)) > 0){
out.write(b, 0, len);
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(out != null){
out.flush();
out.close();
}
if(fin != null){
fin.close();
}
}
}
/**
* 删除本地工程文件目录下所有文件
*
* @param path
*/
private void delAllFile(String path) {
File file = new File(path);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
temp = new File(path + tempList[i]);
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + tempList[i] + "/");
delete(path + tempList[i] + "/");
}
}
}
上面是简单的应用,代码可以实现上传和下载,如果你想了解的更多更详细,可以参照官方api