用ftp下载文件,ftpClient.retrieveFileStream(filename)返回null

long龙儿er 2015-05-27 01:36:24
ftpClient.connect(hostname, port);
boolean loginflag = ftpClient.login(ftpusername, ftppwd);
if (loginflag && FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
{
InputStream inputStream =null;
inputStream=ftpClient.retrieveFileStream("loom.jpg");//返回为空
}

在浏览器中输入:ftp://127.0.0.1:2121/loom.jpg可以得到文件
...全文
19586 22 打赏 收藏 转发到动态 举报
写回复
用AI写文章
22 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_42071412 2018-05-07
  • 打赏
  • 举报
回复
引用 14 楼 w1991x 的回复:
public static String readFtpFile(String fileName ){ FTPClient ftp = new FTPClient(); StringBuilder builder = null; try { ftp.connect(ftpIP,prot); ftp.login(ftpName, ftpPwd); } ftp.enterLocalPassiveMode(); InputStream ins = ftp.retrieveFileStream(fileName); BufferedReader reader = new BufferedReader(new InputStreamReader(ins, "UTF-8")); String line; builder = new StringBuilder(150); while ((line = reader.readLine()) != null) { builder.append(line); } reader.close(); if (ins != null) { ins.close(); } // 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题 ftp.getReply(); } catch (IOException e) { e.printStackTrace(); }finally{ try { ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return builder.toString(); } 这是我一直在用ftp文件下载,可以参考一下
强,有用
别逗,写BUG呢 2017-12-26
  • 打赏
  • 举报
回复
666 getReply()解决了我查了半天的问题
qq_16186513 2017-11-07
  • 打赏
  • 举报
回复
等一个大佬
naive555 2017-10-13
  • 打赏
  • 举报
回复
同问以上方法 哪个好用 为啥还没结帖
Vatory 2017-07-05
  • 打赏
  • 举报
回复
// mFtpClient.changeToParentDirectory(); 这句话要注释掉,同时写服务器文件目录的时候要用完整的目录,我是这么解决的
月明星稀灬 2016-11-25
  • 打赏
  • 举报
回复
这方法是做说明用的??? getReply 解决了我的问题。
ZXW152127 2016-05-24
  • 打赏
  • 举报
回复
ftpClient.getReply();这个可以解决!帮助你们的请给我点赞
jucks2611 2016-05-05
  • 打赏
  • 举报
回复
outputStream = response.getOutputStream(); ftpEngine.ftpClient.retrieveFile(filepath, outputStream); 可以使用retrieveFile代替
w1991x 2016-04-18
  • 打赏
  • 举报
回复
public static String readFtpFile(String fileName ){ FTPClient ftp = new FTPClient(); StringBuilder builder = null; try { ftp.connect(ftpIP,prot); ftp.login(ftpName, ftpPwd); } ftp.enterLocalPassiveMode(); InputStream ins = ftp.retrieveFileStream(fileName); BufferedReader reader = new BufferedReader(new InputStreamReader(ins, "UTF-8")); String line; builder = new StringBuilder(150); while ((line = reader.readLine()) != null) { builder.append(line); } reader.close(); if (ins != null) { ins.close(); } // 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题 ftp.getReply(); } catch (IOException e) { e.printStackTrace(); }finally{ try { ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return builder.toString(); } 这是我一直在用ftp文件下载,可以参考一下
  • 打赏
  • 举报
回复
我也遇到这个问题了,你们解决了吗
haozi92 2016-03-02
  • 打赏
  • 举报
回复
我也遇到了这个问题,请问怎么解决
AlenCheng 2015-12-09
  • 打赏
  • 举报
回复
引用 9 楼 LuckFu 的回复:
现在我也遇到了这个问题。楼主解决了没?
这位仁兄,你这个问题解决了吗?
AlenCheng 2015-12-09
  • 打赏
  • 举报
回复
楼主解决了吗?
Jeff Dauglas 2015-07-01
  • 打赏
  • 举报
回复
现在我也遇到了这个问题。楼主解决了没?
long龙儿er 2015-05-27
  • 打赏
  • 举报
回复
引用 5 楼 birdsaction 的回复:
试试 currentDirectory方法看看目录路径可对。

设置被动模式之后,有那个异常,怎么是127.0.0.1呢?我设置的是10.0.2.2,还有那个异常端口号是怎么来的
long龙儿er 2015-05-27
  • 打赏
  • 举报
回复
引用 5 楼 birdsaction 的回复:
试试 currentDirectory方法看看目录路径可对。
这个知道了,路径是对的。。。
long龙儿er 2015-05-27
  • 打赏
  • 举报
回复
引用 5 楼 birdsaction 的回复:
试试 currentDirectory方法看看目录路径可对。
非常感谢,但是这个没懂。。。在哪里用这个函数
Birds2018 2015-05-27
  • 打赏
  • 举报
回复
试试 currentDirectory方法看看目录路径可对。
long龙儿er 2015-05-27
  • 打赏
  • 举报
回复
引用 3 楼 birdsaction 的回复:
你2个都试试 我也用过这个ftp client。如果是内网应该很容易访问。 你的ftp server 有设置 你也看看
这个在浏览器或者cmd中都能获取到文件,就是程序里面就不行了。文件 loom.jpg就是直接放在设置站点的目录下的
Birds2018 2015-05-27
  • 打赏
  • 举报
回复
你2个都试试 我也用过这个ftp client。如果是内网应该很容易访问。 你的ftp server 有设置 你也看看
加载更多回复(2)
public class FTPUtil { private FTPClient ftpClient=null; private boolean result = false; private FileInputStream fis; String ftpHost = "10.16.111.111"; String port = 21 String ftpUserName = "ftpuser11; String ftpPassword = "1234561"; /** * 登录服务器 * @param ftpInfo * @return * @throws IOException */ public FTPClient login() throws IOException { ftpClient = new FTPClient(); ftpClient.connect(ftpHost); boolean login = ftpClient.login(ftpUserName,ftpPassword); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } if(login){ System.out.println("ftp连接成功!"); }else{ System.out.println("ftp连接失败!"); } //ftpClient.setControlEncoding("GBK"); return ftpClient; } /** * 字符串作为文件上传指定目录 下 * @param content 源字符串 * @param uploadDir 上传目录 * @param ftpFileName 上传文件名称 * @throws Exception */ public void ftpUploadByText(String content ,String uploadDir,String ftpFileName) throws Exception{ try { ftpClient = this.login(); //创建目录 createDir(ftpClient,uploadDir); // 设置上传目录 这个也应该用配置文件读取 ftpClient.changeWorkingDirectory(uploadDir); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); String fileName = new String(ftpFileName.getBytes("GBK"),"iso-8859-1"); OutputStream os = ftpClient.storeFileStream(fileName); byte[] bytes = content.getBytes(); os.write(bytes); os.flush(); os.close(); } catch (Exception e) { ftpClient.disconnect(); ftpClient = null; e.printStackTrace(); throw e; }finally{ ftpClient.disconnect(); ftpClient = null; } } /** * 移动文件 * @param ftpInfo * @return * @throws Exception */ public boolean moveFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.moveFile(ftpClient, ftpInfo.getChangeWorkingDirectoryPath(), ftpInfo.getFilePath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 删除文件 * @param ftpInfo * @return * @throws Exception */ public boolean deleteFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.deleteByFolder(ftpClient, ftpInfo.getChangeWorkingDirectoryPath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 实现文件的移动,这里做的是一个文件夹下的所有内容移动到新的文件, * 如果要做指定文件移动,加个判断判断文件名 * 如果不需要移动,只是需要文件重命名,可以使用ftp.rename(oleName,newName) * @param ftp * @param oldPath * @param newPath * @return */ public boolean moveFile(FTPClient ftp,String oldPath,String newPath){ boolean flag = false; try { ftp.changeWorkingDirectory(oldPath); ftp.enterLocalPassiveMode(); //获取文件数组 FTPFile[] files = ftp.listFiles(); //新文件夹不存在则创建 if(!ftp.changeWorkingDirectory(newPath)){ ftp.makeDirectory(newPath); } //回到原有工作目录 ftp.changeWorkingDirectory(oldPath); for (FTPFile file : files) { if(file.isDirectory()) { moveFile(ftp,oldPath+file.getName()+"/" ,newPath+file.getName()+"/"); }else{ //转存目录 flag = ftp.rename(oldPath+new String(file.getName().getBytes("GBK"),"ISO-8859-1"), newPath+"/"+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } if(flag){ System.out.println(file.getName()+"移动成功"); }else{ System.out.println(file.getName()+"移动失败"); } } ftp.removeDirectory(new String(oldPath.getBytes("GBK"),"ISO-8859-1")); } catch (Exception e) { e.printStackTrace(); System.out.println("移动文件失败"); } return flag; } /** * 删除FTP上指定文件夹下文件及其子文件方法,添加了对中文目录的支持 * @param ftp FTPClient对象 * @param FtpFolder 需要删除的文件夹 * @return */ public boolean deleteByFolder(FTPClient ftp,String FtpFolder){ boolean flag = false; try { ftp.changeWorkingDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); ftp.enterLocalPassiveMode(); FTPFile[] files = ftp.listFiles(); for (FTPFile file : files) { //判断为文件则删除 if(file.isFile()){ ftp.deleteFile(FtpFolder+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } //判断是文件夹 if(file.isDirectory()){ String childPath = FtpFolder +file.getName()+ "/"; //递归删除子文件夹 deleteByFolder(ftp,childPath); } } //循环完成后删除文件夹 flag = ftp.removeDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); if(flag){ System.out.println(FtpFolder+"文件夹删除成功"); }else{ System.out.println(FtpFolder+"文件夹删除成功"); } } catch (Exception e) { e.printStackTrace(); System.out.println("删除失败"); } return flag; } /** * 创建目录 * @param createpath * @param sftp */ public void createDir(FTPClient ftpClient,String createpath) throws Exception { try { if(ftpClient.changeWorkingDirectory(createpath)) { return; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if(!ftpClient.changeWorkingDirectory(filePath.toString())) { ftpClient.makeDirectory(filePath.toString()); ftpClient.changeWorkingDirectory(filePath.toString()); } } ftpClient.changeWorkingDirectory(createpath); }catch (Exception e) { e.printStackTrace(); throw new Exception("创建路径错误:" + createpath); } } }
package ftp; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import java.io.FileInputStream; import java.io.IOException; import sun.net.TelnetOutputStream; import sun.net.ftp.FtpClient; public class MainCtrl extends HttpServlet { private FtpClient ftpClient; public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html; charset=UTF-8"); try { //连接ftp服务器 connectServer("10.10.1.2", "zz3z2008", "zz3z2008", "upftp"); //上传文件;并返回上传文件的信息 req.setAttribute("inf", upload(req.getParameter("file_name"))); } catch (Exception e) { System.out.println(e.toString()); req.setAttribute("inf", e.toString()); req.getRequestDispatcher("view_inf.jsp").forward(req, resp); return; } finally { if (ftpClient != null) { ftpClient.closeServer(); } } req.getRequestDispatcher("view_inf.jsp").forward(req, resp); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } //连接ftp服务器 private void connectServer(String server, String user, String password, String path) throws IOException { // server:FTP服务器的IP地址;user:登录FTP服务器的用户名 // password:登录FTP服务器的用户名的口令;path:FTP服务器上的路径 ftpClient = new FtpClient(); ftpClient.openServer(server); ftpClient.login(user, password); //path是ftp服务下主目录的子目录 if (path.length() != 0) ftpClient.cd(path); //用2进制上传 ftpClient.binary(); } //上传文件;并返回上传文件的信息 private String upload(String filename) throws Exception { TelnetOutputStream os = null; FileInputStream is = null; try { //"upftpfile"用ftp上传后的新文件名 //os = ftpClient.put("upftpfile"); os = ftpClient.put("MainCtrl.zip"); java.io.File file_in = new java.io.File(filename); if (file_in.length()==0) { return "上传文件为空!"; } is = new FileInputStream(file_in); byte[] bytes = new byte[1024]; int c; while ((c = is.read(bytes)) != -1) { os.write(bytes, 0, c); } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } return "上传文件成功!"; } } 文件2:upftp.htm(前台操作页面)内容如下:
ftp客户端ftpclient纯C语言winsock实现socket编程 /* *本程序是2009年计算机网络课程设计作品。 *本程序参考rfc959标准。能准确与遵守此标准的服务器进行信息交互。 *本人不保留任何版权。 *本程序仅供学习研究测试使用。因使用本程序所有或部分代码所产生的任何后果,本人均不负任何法律责任。 *2009年7月13日 */ #include #include #include /*system()*/ #include #pragma comment(lib,"ws2_32.lib") #define ONUM 512 #define MNUM 512 #define FNUM 512 #define pt struct host { char ip[20]; unsigned short port; }; SOCKET ts; fd_set readfds; struct timeval timeval; struct host host; char renum[4]; char ordertemp[ONUM]; char order[ONUM]; char ordercp[ONUM]; char mess[MNUM]; char file[FNUM]; char setpath[FNUM]; char setpathf[FNUM]; int i,door,r,sys,seti;/*i for;door switch;r receive num;sys system state;set set state*/ char *p;/*strtok*/ int printmess(); void input(char ordertemp[]); int ftp(); int user(); int pass(); int command(); int list(); SOCKET createDataSocket(); int set(); int retr(); int stor(); int stor() { char filename[256]; SOCKET ds; int wi; int r2,r3,r4,bsnum,brnum; FILE *fp=NULL; set(); memset(filename,'\0',256); memset(order,'\0',ONUM); for(i=5;ibsnum); }/*while*/ printf("\n"); switch(printmess()) { case 425: case 426: case 451: case 551: case 552:closesocket(ds);fclose(fp);return -1; case 250: case 226:fclose(fp);return 0; default:return 0; } }/*stor*/ int retr() { char filename[256]; unsigned long fsize,wfsize; int r2,wi; SOCKET ds; FILE *fp=NULL; memset(filename,'\0',256); memset(order,'\0',ONUM); for(i=5;i<=200&&ordercp[i]!='\0';i++)order[i-5]=ordercp[i]; strcpy(filename,setpathf); strcat(filename,"\\\\"); strcat(filename,order); ds=createDataSocket(); if(ds==-1)return -1; memset(order,'\0',ONUM); strcpy(order,"type i\r\n");/*type i 二进制 type a ASCII*/ send(ts,order,strlen(order),0); switch(printmess()) { case 421:closesocket(ds);closesocket(ts);sys=0;return 421; case 530:closesocket(ds);sys=1;return -1; case 500: case 501: case 504: case 226:closesocket(ds);return -1; case 200:break; default:closesocket(ds);return -1; } strcat(ordercp,"\r\n"); send(ts,ordercp,strlen(ordercp),0); switch(printmess()) { case 421:closesocket(ds);closesocket(ts);sys=0;return 421; case 530:closesocket(ds);sys=1;return -1; case 450: case 500: case 501: case 550:closesocket(ds);return -1; case 125: case 150:break; default:closesocket(ds);return -1; } set(); system(setpath); fp=fopen(filename,"wb"); if(!fp){printf("create file fail!\n");closesocket(ds);printmess();return -1;} wi=1;fsize=0;wfsize=0; while(wi) { memset(file,'\0',FNUM); r=recv(ds,file,FNUM,0); if(r==SOCKET_ERROR) { printf("file recv error!\n"); closesocket(ds); fclose(fp); return -1; } fsize=fsize+r; if(r==0){wi=0;break;} printf("receive %8d bytes! have received %16d bytes!\r",r,fsize); r2=fwrite(file,sizeof(char),r,fp); fflush(fp);/*这里是关键*/ wfsize=wfsize+r2; printf("write %8d bytes!have written %20d bytes!\r",r2,wfsize); }/*while*/ printf("\n"); switch(printmess()) { case 425: case 426: case 451:closesocket(ds);fclose(fp);return -1; case 250: case 226: closesocket(ds); wi=1; while(wi)if(fclose(fp)==0)wi=0;return 0; default:return 0; } }/*retr()*/ 以下代码请下载本程序。VC++6.0编译通过

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧