//ftp构造
public FTPUtil(String hostname, int port, String userName, String password) {
ftpClient = new FTPClient();
this.hostname = hostname;
this.port = port;
this.userName = userName;
this.password = password;
}
//ftp连接
public boolean connectServer() throws SocketException, IOException {
ftpClient.connect(hostname, port);
boolean isLogin = ftpClient.login(userName, password);
boolean isSetFileType = ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.cwd(rootNode);
ftpClient.enterLocalPassiveMode();
return isLogin && isSetFileType;
}
ftp下载文件
public String downloadFileFromFTP(String ftpFilePath) {
InputStream is = null;
byte[] data = null;
ByteArrayOutputStream swapStream = null;
try {
// 获取ftp上的文件流
is = ftpClient.retrieveFileStream(new String(ftpFilePath.getBytes("GBK"),"ISO-8859-1"));
swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int rev = 0;
while ((rev = is.read(buff, 0, buff.length)) > 0) {
swapStream.write(buff, 0, rev);
}
data = swapStream.toByteArray();
ftpClient.completePendingCommand();
logger.info("FTP文件下载成功!");
} catch (Exception e) {
logger.error("FTP文件下载失败!", e);
} finally {
try {
if (is != null) {
is.close();
}
if (swapStream != null) {
swapStream.close();
}
} catch (IOException e) {
logger.info("关闭流发生异常_"+e);
}
}
return Base64.encodeBase64String(data);
//上传文件
public boolean uploadFile(File localFile, String remoteFile) throws IOException {
FileInputStream is = null;
try {
is = new FileInputStream(localFile);
logger.info("FileInputStream file" + is);
return ftpClient.appendFile(remoteFile, is);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
本文详细介绍了一个FTP客户端的构造和使用方法,包括连接服务器、下载文件和上传文件等核心功能的实现。通过具体代码示例,展示了如何使用Java进行FTP文件传输,以及在过程中可能遇到的异常处理。
1万+

被折叠的 条评论
为什么被折叠?



