|
package com.hellojim.beans;
import sun.net.ftp.*;
import java.util.*;
import sun.net.*;
import java.io.*;
public class FtpTest {
public static void main(String[] args) throws IOException {
byte[] bt = null;
TelnetInputStream getfile;
TelnetOutputStream putfile;
String str;
// 和服务器建立连接,这里的服务器为公司局域网内的一台机器,IP为 192.168.1.46
FtpClient ftp = null;
try {
ftp = new FtpClient("192.168.1.46");
} catch (IOException e) {
e.printStackTrace();
}
str = ftp.getResponseString();
//这里的 getResponseString() 为每操作一步,服务器响应的信息,打印这样的信息,有助于调试程序
System.out.println("step 1:" + str);
/**
* 登陆到Ftp服务器
*/
try {
/**登录到Ftp服务器,这里的用户名(hellojim)和密码(sa)都是事先在192.168.1.46
* 这台机器的Ftp服务器端的Serv-U上添加的,hellojim这个用户的权限已在Serv-U上
* 定义过了(比如对某个文件夹的访问权限啊,只能访问那些目录...),
* 以我的机器为例吧:hellojim这个用户登录上去后,服务器端显示的目录为d:\,并且
* d:\ 下有一个名为 test 的目录
*/
ftp.login("hellojim", "sa");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
str = ftp.getResponseString();
System.out.println("step 2:" + str);
/**
* 下面的代码是打印当前目录列表
*/
TelnetInputStream in = null;
try {
in = ftp.list();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
str = ftp.getResponseString();
System.out.println("step 3:" + str);
try {
bt = new byte[in.available()];
in.read(bt);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
str = new String(bt);
System.out.println("step 4:" + str );
try {
//cd() 方法用来改变当前目录
ftp.cd("test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
str = ftp.getResponseString();
System.out.println("step 5:" + str);
/**
* 下面的代码是打印test目录列表
*/
in = ftp.list();
str = ftp.getResponseString();
System.out.println("step 6:" + str);
bt = new byte[in.available()];
in.read(bt);
str = new String(bt);
System.out.println("step 7:" + str);
str = ftp.getResponseString();
System.out.println("step 8:" + str);
ftp.binary(); //上载二进制文件的代码,如果是上传文本文件的可是写成 ftp.ascii();
//zhangsan.doc 表示上传到服务器上后,这个文件的名字
putfile = ftp.put("zhangsan.doc");
//d:\\lisi.doc 表示上传的本地文件
FileInputStream fs = new FileInputStream("d:\\lisi.doc");
while (true) {
int i = fs.read();
if (i == -1)
break;
else {
putfile.write((byte) i);
putfile.flush();
}
}
putfile.close();
fs.close();
}
}
//附件中有具体的例子
|
|