您的位置:首页 > 编程语言 > Java开发

java FTPClient 文件服务器上传

2014-09-25 08:44 423 查看
public class FileUtils {

/**
* @param ip       FTP 服务器IP
* @param port     FTP 服务使用的端口
* @param username 登录服务器的用户名
* @param password 登录使用的密码
* @param file     要进行上传的文件
* @param fileName 文件的存储名称
* @param path     文件在服务器的存储路径, 如果不存在则创建目录
* @throws Exception
*/
public static void uploadFiles(String ip, int port, String username, String password, File file, String fileName,String path ) throws Exception {
FTPClient ftpClient = null;
FileInputStream ins =  new FileInputStream(file) ;
try {
ftpClient = new FTPClient();
/// 链接文件服务器
ftpClient.connect(ip, port);
/// 登录文件服务器
boolean result = ftpClient.login(username, password);
if(!result){
throw new Exception("文件服务器用户名或密码不正确");
}
/// 设置文件服务器上传格式
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
/// 切换到指定的目录
boolean changeWorkPath = ftpClient.changeWorkingDirectory(path) ;
/// 如果切换不成功则创建目录
if (!changeWorkPath) {
boolean change = createDirectory(path , ftpClient) ;
if(!change){
throw new Exception("文件服务器切换工作目录失败");
}
}
/// 进行文件传送
if (ftpClient.storeFile(fileName,ins)) {
} else {
throw new Exception("文件上传失败!");
}
} finally {
if (ftpClient != null){
if (ftpClient.isConnected()) {
try {/// 关闭链接
ftpClient.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
throw ioe;
}
}
}
if(ins != null ){
ins.close() ;
}
}
}
/**
* 在ftp服务器创建目录
*/
public static boolean createDirectory(String path, FTPClient ftpClient)
throws IOException {
boolean flag = false ;
String[] pathes = path.split("/") ;
for (int i = 0; i < pathes.length; i++) {
ftpClient.makeDirectory(pathes[i]);
flag = ftpClient.changeWorkingDirectory(pathes[i]);
}
return flag ;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: