下面的例子,只是让自己对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是文件名,
下面的代码就可以用于下载此文件
- URL url = new URL("ftp://ftp.neu.edu.cn/bt.neu6.edu.cn.txt");
- URLConnection con = url.openConnection();
- InputStream in = con.getInputStream();
- String r = inputstreamToString(in);
- System.out.println(r);
- private static String inputstreamToString(InputStream in) {
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- StringBuffer buffer = new StringBuffer();
- String str = null;
- try {
- while ((str = reader.readLine()) != null) {
- buffer.append(str + "\r\n");
- }
- return buffer.toString();
- } catch (IOException e) {
- return buffer.toString();
- }
- }
下面是实现上传
- URL url = new URL("ftp://ftp.neu.edu.cn/netinstall/1.txt");// 要上传的文件地址
- URLConnection con = url.openConnection();
- con.getOutputStream().write("文件内容".getBytes("GB2312"));
- 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)