edtFTPj的FileTransferClient类简单易用,而且下载的组件包中文档丰富,参考使用,完全能满足自己需要。
下载地址为:http://www.enterprisedt.com/index.html
废话不多说,上代码:
- public class EdtFtpFreeTest {
- public static void main(String[] args) {
- String ftp_url = "127.0.0.1";
- String ftp_username = "username";
- String ftp_password = "password";
- String ftp_path = "remote path";
- // 本地文件路径
- String file_path = "local path name";
- //上传服务器上文件名
- String remoteFile = "remote file name";
- FileTransferClient ftp = new FileTransferClient();
- try {
- ftp.setRemoteHost(ftp_url);
- ftp.setUserName(ftp_username);
- ftp.setPassword(ftp_password);
- ftp.connect();
- ftp.setContentType(FTPTransferType.BINARY);
- ftp.changeDirectory(ftp_path);
- //直接上传
- ftp.uploadFile(file_path, remoteFile, WriteMode.RESUME);
- //构造文件流上传
- OutputStream os = ftp.uploadStream(remoteFile);
- FileInputStream is = new FileInputStream(file_path);
- byte[] bytes = new byte[1024];
- int c;
- while ((c = is.read(bytes)) != -1) {
- os.write(bytes, 0, c);
- }
- is.close();
- os.close();
- is = null;
- os = null;
- ftp.disconnect();
- } catch (FTPException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
public class EdtFtpFreeTest { public static void main(String[] args) { String ftp_url = "127.0.0.1"; String ftp_username = "username"; String ftp_password = "password"; String ftp_path = "remote path"; // 本地文件路径 String file_path = "local path name"; //上传服务器上文件名 String remoteFile = "remote file name"; FileTransferClient ftp = new FileTransferClient(); try { ftp.setRemoteHost(ftp_url); ftp.setUserName(ftp_username); ftp.setPassword(ftp_password); ftp.connect(); ftp.setContentType(FTPTransferType.BINARY); ftp.changeDirectory(ftp_path); //直接上传 ftp.uploadFile(file_path, remoteFile, WriteMode.RESUME); //构造文件流上传 OutputStream os = ftp.uploadStream(remoteFile); FileInputStream is = new FileInputStream(file_path); byte[] bytes = new byte[1024]; int c; while ((c = is.read(bytes)) != -1) { os.write(bytes, 0, c); } is.close(); os.close(); is = null; os = null; ftp.disconnect(); } catch (FTPException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }