1.连接
public static FTPClient client_ = new FTPClient();
public static FTPClient client2_ = new FTPClient();
static {
try {
client_.connect("xx.xx.xx.xx", 21);
client_.login("anonymous", "lfq");
client_.setConnectTimeout(0);
client_.enterLocalPassiveMode();
client_.setControlEncoding("UTF-8");
client_.setFileType(FTPClient.BINARY_FILE_TYPE);
client2_.connect("xx.xx.xx.xx", 21);
client2_.login("username", "password");
client2_.setConnectTimeout(0);
client2_.enterLocalPassiveMode();
client2_.setControlEncoding("UTF-8");
client2_.setFileType(FTPClient.BINARY_FILE_TYPE);
client2_.changeWorkingDirectory("path");
} catch (IOException e) {
e.printStackTrace();
}
}
其中login中的两个参数是用户名密码,如果没有相应配置可以使用"anonymous",代表匿名登录,密码任意
2.传输文件
public void transFile(FTPClient c1, FTPClient c2, String path, String filename) throws IOException {
InputStream inputStream = c1.retrieveFileStream(path);
OutputStream outputStream = c2.storeFileStream(filename);
Util.copyStream(inputStream, outputStream, 1024 * 16);
Util.closeQuietly(inputStream);
Util.closeQuietly(outputStream);
client_.disconnect();
client2_.disconnect();
}
3.可能出现的问题
socket read error
如果频繁下载上传文件,可能会由于服务器配置策略或者其他网络原因,导致retrieveFileStream返回的inputStream 为null,
在我尝试了其他博主给出的解决办法后,依然会有此问题。
最后我索性尝试最笨办法----每次下载完文件后断开连接,重新下载时再重新连接即可!