[JAVA]Apache FTPClient操作“卡死”问题的分析和解决(二)
tTimeoutSecond * 1000);
34 ftp.setConnectTimeout(connectTimeoutSecond * 1000);
35 ftp.setDataTimeout(dataTimeoutSecond * 1000);
36 }
37
38 /**
39 * Connects to FTP server.
40 *
41 * @param host
42 * FTP server address or name
43 * @param port
44 * FTP server port
45 * @param user
46 * user name
47 * @param password
48 * user password
49 * @param isTextMode
50 * text / binary mode switch
51 * @throws IOException
52 * on I/O errors
53 */
54 public void connect(String host, int port, String user, String password, boolean isTextMode) throws IOException {
55 // Connect to server.
56 try {
57 ftp.connect(host, port);
58 } catch (UnknownHostException ex) {
59 throw new IOException("Can't find FTP server '" + host + "'");
60 }
61
62 // Check rsponse after connection attempt.
63 int reply = ftp.getReplyCode();
64 if (!FTPReply.isPositiveCompletion(reply)) {
65 disconnect();
66 throw new IOException("Can't connect to server '" + host + "'");
67 }
68
69 if (user == "") {
70 user = ANONYMOUS_LOGIN;
71 }
72
73 // Login.
74 if (!ftp.login(user, password)) {
75 is_connected = false;
76 disconnect();
77 throw new IOException("Can't login to server '" + host + "'");
78 } else {
79 is_connected = true;
80 }
81
82 // Set data transfer mode.
83 if (isTextMode) {
84 ftp.setFileType(FTP.ASCII_FILE_TYPE);
85 } else {
86 ftp.setFileType(FTP.BINARY_FILE_TYPE);
87 }
88 }
89
90 /**
91 * Uploads the file to the FTP server.
92 *
93 * @param ftpFileName
94 * server file name (with absolute path)
95 * @param localFile
96 * local file to upload
97 * @throws IOException
98 * on I/O errors
99 */
100 public void upload(String ftpFileName, File localFile) throws IOException {
101 // File check.
102 if (!localFile.exists()) {
103 throw new IOException("Can't upload '" + localFile.getAbsolutePath() + "'. This file doesn't exist.");
104 }
105
106 // Upload.
107 InputStream in = null;
108 try {
109
110 // Use passive mode to pass firewalls.
111 ftp.enterLocalPassiveMode();
112
113 in = new BufferedInputStream(new FileInputStream(localFile));
114 if (!ftp.storeFile(ftpFileName, in)) {
115 throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");
116 }
117
118 } finally {
119 try {
120 in.close();
121 } catch (IOException ex) {
122 }
123 }
124 }
125
126 /**
127 * Downloads the file from the FTP server.
128 *
129 * @param ftpFileName
130 * server file name (with absolute path)
131 * @param localFile
132 * local file to download into
133 * @throws IOException
134 * on I/O errors
135 */
136 public void download(String ftpFileName, File localFile) throws IOException {