现在的位置: 首页 > 综合 > 正文

FTP~~URL对FTP的支持原因

2014年09月05日 ⁄ 综合 ⁄ 共 1678字 ⁄ 字号 评论关闭

下面的例子,只是让自己对FTP有一个简单的认识,没有多大的意义,自己练习一下.同时发现了原来JDK6.0以及将jarkarta的net框架收入,URL中对FTP的支持就是使用这个框架啊!

FTP的URL格式如下

ftpurl         = “ftp://” login [ “/” fpath [ “;type=” ftptype ]]
fpath          = fsegment *[ “/” fsegment ]
fsegment       = *[ uchar | “?” | “:” | “@” | “&” | “=” ]
ftptype        = “A” | “I” | “D” | “a” | “i” | “d”

简单示例

ftp://<用户名>:<密码>@<主机名>/文件URL;type=<FTP类型>

ftp://ftp.neu.edu.cn/bt.neu6.edu.cn.txt 其中bt.neu6.edu.cn.txt是文件名,

下面的代码就可以用于下载此文件

  1. URL url = new URL("ftp://ftp.neu.edu.cn/bt.neu6.edu.cn.txt");
  2. URLConnection con = url.openConnection();
  3. InputStream in = con.getInputStream();
  4. String r = inputstreamToString(in);
  5. System.out.println(r);
  6.     private static String inputstreamToString(InputStream in) {
  7.         BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  8.         StringBuffer buffer = new StringBuffer();
  9.         String str = null;
  10.         try {
  11.             while ((str = reader.readLine()) != null) {
  12.                 buffer.append(str + "\r\n");
  13.             }
  14.             return buffer.toString();
  15.         } catch (IOException e) {
  16.             return buffer.toString();
  17.         }
  18.     }

下面是实现上传

  1.     URL url = new URL("ftp://ftp.neu.edu.cn/netinstall/1.txt");// 要上传的文件地址
  2.             URLConnection con = url.openConnection();
  3.             con.getOutputStream().write("文件内容".getBytes("GB2312"));
  4.             con.getOutputStream().close();

由于这个是我们学校的FTP服务器,会抛出异常,这就让我知道了原来URL对FTP的支持也是使用jarkarta的net框架,也就是说JDK6.0已经收入了这个框架了。异常信息如下

sun.net.ftp.FtpProtocolException: 553 Anonymous users may not overwrite existing files

 at sun.net.ftp.FtpClient.openDataConnection(Unknown Source)
 at sun.net.ftp.FtpClient.put(Unknown Source)
 at sun.net.www.protocol.ftp.FtpURLConnection.getOutputStream(Unknown Source)
 at Test.Test.main(Test.java:24)

抱歉!评论已关闭.