项目实践中遇到Ftp传输问题,在这里做个专辑。
第一篇还是介绍一下sun提供的FtpClient.这个也是网上说的最多的,在这里我只是给出例程,不再做详细的解释。sun提供的FtpClient简单宜用,不支持任何加密方式;并没有提供相应的api,所以给我们调试带来不便,与其说是sun足够自信说这个组件简单到不用api就可以完全满足应用,还不如说不负责任。其实在开发中会遇到各种问题,实践中就遇到上传文件到一定数量级后传输会变慢(很慢),但程序并不报错;用ftp客户端桌面软件测试发现连续传输1000个左右文件报错率为4,可能FtpClient在开发时候对异常捕捉不全面。但如果在小数据量和没有用加密方式认证和传输的情况下,FtpClient仍不失是一个很好的选择。
下面是例程:
- publicclassTestFtpClient{
- /**
- *@paramargs
- */
- publicstaticvoidmain(String[]args){
- FtpClientftpClient;
- //server:FTP服务器的IP地址
- Stringserver="127.0.0.1";
- //user:登录FTP服务器的用户名
- Stringuser="username";
- //password:登录FTP服务器的用户名的口令
- Stringpassword="password";
- //path:FTP服务器上的路径
- Stringpath="/path/";
- //要上传本地文件路径
- Stringfilename="D:"+File.separator+"test.txt";
- //上传服务器上文件名
- StringftpFile="test.txt";
- try{
- ftpClient=newFtpClient(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();
- TelnetOutputStreamos=null;
- FileInputStreamis=null;
- os=ftpClient.put(ftpFile);
- Filefile_in=newFile(filename);
- if(file_in.length()==0){
- thrownewException("上传文件为空!");
- }
- is=newFileInputStream(file_in);
- byte[]bytes=newbyte[1024];
- intc;
- while((c=is.read(bytes))!=-1){
- os.write(bytes,0,c);
- }
- System.out.println("上传文件成功!");
- is.close();
- os.close();
- }catch(FileNotFoundExceptione){
- e.printStackTrace();
- }catch(IOExceptione){
- e.printStackTrace();
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- }