今天工作用需要用到ftp上传整个文件,在网上查了资料一直报错,都困扰我一天了,代码如下:
package cn.lsh.test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.StringTokenizer;
import sun.net.ftp.FtpClient;
public class FtpUtils {
private String ip="";
private String username="";
private String password ="";
private int port= -1;
private String path ="";
FtpClient ftpClient =null;
FileInputStream is =null;
OutputStream os = null;
public FtpUtils(String serverIP,String username,String password){
this.ip =serverIP;
this.username = username;
this.password = password;
}
public FtpUtils(String serverIP,String username,String password,int port){
this.ip =serverIP;
this.username = username;
this.password = password;
this.port =port;
}
/*
* 连接ftp服务器
*/
public boolean connectServer(){
ftpClient = new FtpClient();
try {
if(this.port != -1){
ftpClient.openServer(this.ip,this.port);
}else{
ftpClient.openServer(this.ip);
}
ftpClient.login(this.username, this.password);
if(path.length() != 0){
ftpClient.cd(path);
}
ftpClient.binary();
System.out.println("已登录到\""+ftpClient.pwd() +"\"目录");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/*
* 断开ftp服务器连接
*/
public boolean closeServer(){
try{
if(is != null){
is.close();
}
if(os != null){
os.close();
}
if(ftpClient != null){
ftpClient.closeServer();
}
System.out.println("已从服务器断开连接");
return true;
}catch(IOException e){
e.printStackTrace();
return false;
}
}
/*
* 在当前目录下创建文件夹
*/
public boolean createDir(String dir){
try{
ftpClient.ascii();
StringTokenizer s = new StringTokenizer(dir, "/");
s.countTokens();
String pathName = ftpClient.pwd();
while(s.hasMoreElements()){
pathName = pathName + "/" + (String)s.nextElement();
try{
ftpClient.sendServer("MKD"+pathName+"/n/r");
}catch(Exception e){
e =null;
return false;
}
ftpClient.readServerResponse();
}
ftpClient.binary();
return true;
}catch(IOException e1){
e1.printStackTrace();
return false;
}
}
//测试!!
public static void main(String[] args){
FtpUtils ftp = new FtpUtils("127.0.0.1", "lsh", "lsh123");
ftp.connectServer();
ftp.createDir("testDir");
ftp.closeServer();
}
}
报错信息:
已登录到"/"目录
sun.net.ftp.FtpProtocolException: TYPE I:500 '
TYPE I': command not understood.
at sun.net.ftp.FtpClient.issueCommandCheck(Unknown Source)
at sun.net.ftp.FtpClient.binary(Unknown Source)
at cn.lsh.test.FtpUtils.createDir(FtpUtils.java:94)
at cn.lsh.test.FtpUtils.main(FtpUtils.java:105)
已从服务器断开连接
我要是把
ftpClient.sendServer("MKD"+pathName+"\n\r");改成
ftpClient.sendServer("MKD"+pathName+"/n/r");
程序运行很长时间,最后报socket错误!
我也是崩溃了!