项目实践中遇到Ftp传输问题,在这里做个专辑。
第一篇还是介绍一下sun提供的FtpClient.这个也是网上说的最多的,在这里我只是给出例程,不再做详细的解释。sun提供的FtpClient简单宜用,不支持任何加密方式;并没有提供相应的api,所以给我们调试带来不便,与其说是sun足够自信说这个组件简单到不用api就可以完全满足应用,还不如说不负责任。其实在开发中会遇到各种问题,实践中就遇到上传文件到一定数量级后传输会变慢(很慢),但程序并不报错;用ftp客户端桌面软件测试发现连续传输1000个左右文件报错率为4,可能FtpClient在开发时候对异常捕捉不全面。但如果在小数据量和没有用加密方式认证和传输的情况下,FtpClient仍不失是一个很好的选择。
下面是例程:
Java代码
-
public class TestFtpClient {
-
-
/**
-
* @param args
-
*/
-
public static void main(String[] args) {
- FtpClient ftpClient;
-
// server:FTP服务器的IP地址
-
String server = "127.0.0.1";
-
// user:登录FTP服务器的用户名
-
String user = "username";
-
// password:登录FTP服务器的用户名的口令
-
String password = "password";
-
// path:FTP服务器上的路径
-
String path = "/path/";
-
// 要上传本地文件路径
-
String filename = "D:" + File.separator + "test.txt";
-
// 上传服务器上文件名
-
String ftpFile = "test.txt";
-
-
try {
-
-
ftpClient = new FtpClient(server);
-
//ftpClient.openServer(server,21);
- ftpClient.login(user, password);
-
System.out.println("Login .......");
-
-
// path是ftp服务下主目录的子目录
-
if (path.length() != 0)
- ftpClient.cd(path);
-
// 用2进制上传
- ftpClient.binary();
-
-
TelnetOutputStream os = null;
-
FileInputStream is = null;
-
- os = ftpClient.put(ftpFile);
-
File file_in = new File(filename);
-
if (file_in.length() == 0) {
-
throw new Exception("上传文件为空!");
- }
-
is = new FileInputStream(file_in);
-
byte[] bytes = new byte[1024];
-
int c;
-
while ((c = is.read(bytes)) != -1) {
-
os.write(bytes, 0, c);
- }
-
-
System.out.println("上传文件成功!");
- is.close();
- os.close();
-
} catch (FileNotFoundException e) {
- e.printStackTrace();
-
} catch (IOException e) {
- e.printStackTrace();
-
} catch (Exception e) {
- e.printStackTrace();
- }
-
- }
- }
public class TestFtpClient {
/**
* @param args
*/
public static void main(String[] args) {
FtpClient ftpClient;
// server:FTP服务器的IP地址
String server = "127.0.0.1";
// user:登录FTP服务器的用户名
String user = "username";
// password:登录FTP服务器的用户名的口令
String password = "password";
// path:FTP服务器上的路径
String path = "/path/";
// 要上传本地文件路径
String filename = "D:" + File.separator + "test.txt";
// 上传服务器上文件名
String ftpFile = "test.txt";
try {
ftpClient = new FtpClient(server);
//ftpClient.openServer(server,21);
ftpClient.login(user, password);
System.out.println("Login .......");
// path是ftp服务下主目录的子目录
if (path.length() != 0)
ftpClient.cd(path);
// 用2进制上传
ftpClient.binary();
TelnetOutputStream os = null;
FileInputStream is = null;
os = ftpClient.put(ftpFile);
File file_in = new File(filename);
if (file_in.length() == 0) {
throw new Exception("上传文件为空!");
}
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println("上传文件成功!");
is.close();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}