远程写FTP文件和文件夹

 

    远程写FTP文件和文件夹,jar包commons-net-3.3.jar

 

 

	/**
	 * 向ftp写文件,可以多个
	 * @param c
	 * @param path :a/pdf/82jf2ijf2fs
	 * @param files
	 * @return
	 */
	public static boolean writeFTPFiles(FTPConnection c,String path,List<File> files){
		FTPClient ftp = new FTPClient();
		try {
			ftp.connect(c.getIp(), c.getPort()); // IP地址和端口 
			// 用户名和密码,匿名登陆的话用户名为anonymous,密码为非空字符串
			boolean bool = ftp.login(c.getUsername(),c.getPassword()); 
			if (!bool) {
				throw new Exception("username or password not correct!");
			}
			System.out.print(ftp.getReplyString());
			int reply = ftp.getReplyCode();

			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				throw new Exception("FTP server refused connection.");
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
			ftp.changeWorkingDirectory(c.getDirectory());
			String[]ps = path.split("/");
			for (String p : ps) {
				String[]arr = ftp.listNames();
				List<String> list = Arrays.asList(arr);
				if (!list.contains(p)) {
					ftp.makeDirectory(p);
				}
				ftp.changeWorkingDirectory(p);
			}
//			ftp.changeToParentDirectory()
			for (File file : files) {
//				String text = read(file, "iso-8859-1");
//				InputStream in = new ByteArrayInputStream(text.getBytes("iso-8859-1"));
				InputStream in = new FileInputStream(file);
				ftp.storeFile(new String(file.getName().getBytes("utf-8"),"iso-8859-1"), in);
				in.close();
			}
			ftp.logout();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally{
			if (ftp.isConnected()) {  
				try {  
					ftp.disconnect();  
				} catch (Exception e) {  
					e.printStackTrace();  
				}  
			}  
		}
		
	}
	/**
	 * 复制文件夹及内容到ftp上
	 * @param c
	 * @param path :a/pdf/82jf2ijf2fs
	 * @param directory
	 * @return
	 */
	public static boolean writeFTPDirectory(FTPConnection c,String path,File directory){
		FTPClient ftp = new FTPClient();
		try {
			ftp.connect(c.getIp(), c.getPort()); // IP地址和端口 
			boolean bool = ftp.login(c.getUsername(),c.getPassword()); // 用户名和密码,匿名登陆的话用户名为anonymous,密码为非空字符串
			if (!bool) {
				throw new Exception("username or password not correct!");
			}
			System.out.print(ftp.getReplyString());
			int reply = ftp.getReplyCode();
			
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				throw new Exception("FTP server refused connection.");
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
			ftp.changeWorkingDirectory(c.getDirectory());
			if (StringUtil.toString(path, null)!=null) {
				String[]ps = path.split("/");
				for (String p : ps) {
					String[]arr = ftp.listNames();
					List<String> list = Arrays.asList(arr);
					if (!list.contains(p)) {
						ftp.makeDirectory(p);
					}
					ftp.changeWorkingDirectory(p);
				}
			}
//			ftp.changeToParentDirectory()
			ftp.makeDirectory(directory.getName());
			ftp.changeWorkingDirectory(directory.getName());
			File[] files = directory.listFiles();
			for (File file : files) {
//				String text = read(file, "iso-8859-1");
//				InputStream in = new ByteArrayInputStream(text.getBytes("iso-8859-1"));
				InputStream in = new FileInputStream(file);
				ftp.storeFile(new String(file.getName().getBytes("utf-8"),"iso-8859-1"), in);
				in.close();
			}
			ftp.logout();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally{
			if (ftp.isConnected()) {  
				try {  
					ftp.disconnect();  
				} catch (Exception e) {  
					e.printStackTrace();  
				}  
			}  
		}
		
	}
	/**
	 * 读取ftp文件内容
	 * @param c
	 * @param f
	 * @return
	 */
	public static String readFTPFile(FTPConnection c,String path,String f){
		
		try {
			FTPClient ftp = new FTPClient();
			ftp.setControlKeepAliveTimeout(6000); // set timeout to 6s
			ftp.connect(c.getIp(), c.getPort()); // IP地址和端口 
			boolean bool = ftp.login(c.getUsername(),c.getPassword()); // 用户名和密码,匿名登陆的话用户名为anonymous,密码为非空字符串
			if (!bool) {
				throw new Exception("username or password not correct!");
			}
			System.out.print(ftp.getReplyString());
			int reply = ftp.getReplyCode();

			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				throw new Exception("FTP server refused connection.");
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
			ftp.changeWorkingDirectory(c.getDirectory());
			
			String[]ps = path.split("/");
			for (String p : ps) {
				String[]arr = ftp.listNames();
				List<String> list = Arrays.asList(arr);
				if (!list.contains(p)) {
					ftp.makeDirectory(p);
				}
				ftp.changeWorkingDirectory(p);
			}
			
			InputStream in = ftp.retrieveFileStream(f);
			InputStreamReader isr = new InputStreamReader(in,"GBK");
			BufferedReader br =  new BufferedReader(isr);
			StringBuffer sb  = new StringBuffer();
			String str = null;
			while ((str=br.readLine())!=null) {
				sb.append(str);
				sb.append("\n");
			}
			br.close();
			isr.close();
			in.close();
			
			ftp.logout();
			String content = sb.toString();
//			System.out.println(content);
			return content;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
			
		
	}
	/**
	 * 读取ftp文件内容,写到本地
	 * @param c
	 * @param f 文件名
	 * @param localFile 本地文件path
	 * @return
	 */
	public static boolean writeLocalFile(FTPConnection c,String path,String f,String localFile){
		
		try {
			FTPClient ftp = new FTPClient();
			ftp.setControlKeepAliveTimeout(6000); // set timeout to 6s
			ftp.connect(c.getIp(), c.getPort()); // IP地址和端口 
			boolean bool = ftp.login(c.getUsername(),c.getPassword()); // 用户名和密码,匿名登陆的话用户名为anonymous,密码为非空字符串
			if (!bool) {
				throw new Exception("username or password not correct!");
			}
			System.out.print(ftp.getReplyString());
			int reply = ftp.getReplyCode();
			
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				throw new Exception("FTP server refused connection.");
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
			ftp.changeWorkingDirectory(c.getDirectory());
			String[]ps = path.split("/");
			for (String p : ps) {
				String[]arr = ftp.listNames();
				List<String> list = Arrays.asList(arr);
				if (!list.contains(p)) {
					return false;
				}
				ftp.changeWorkingDirectory(p);
			}
			InputStream in = ftp.retrieveFileStream(f);
			if (in==null) {
				return false;
			}
			OutputStream out = new FileOutputStream(localFile);
			int ch = -1;
			while ((ch=in.read())!=-1) {
				out.write(ch);
			}
			in.close();
			out.close();
			File file = new File(localFile);
			if (file.exists()) {
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.getMessage());
			return false;
		}
		
		
	}
	
	/**
	 * 读取ftp文件内容,写到本地
	 * @param c
	 * @param f 文件名
	 * @param localFile 本地文件path
	 * @return
	 */
	public static boolean existFTPFile(FTPConnection c,String path,String f){
		
		try {
			FTPClient ftp = new FTPClient();
			ftp.setControlKeepAliveTimeout(6000); // set timeout to 6s
			ftp.connect(c.getIp(), c.getPort()); // IP地址和端口 
			boolean bool = ftp.login(c.getUsername(),c.getPassword()); // 用户名和密码,匿名登陆的话用户名为anonymous,密码为非空字符串
			if (!bool) {
				throw new Exception("username or password not correct!");
			}
			System.out.print(ftp.getReplyString());
			int reply = ftp.getReplyCode();
			
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				throw new Exception("FTP server refused connection.");
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
			ftp.changeWorkingDirectory(c.getDirectory());
			String[]ps = path.split("/");
			for (String p : ps) {
				String[]arr = ftp.listNames();
				List<String> list = Arrays.asList(arr);
				if (!list.contains(p)) {
					return false;
				}
				ftp.changeWorkingDirectory(p);
			}
			InputStream in = ftp.retrieveFileStream(f);
			if (in==null) {
				return false;
			}else{
				in.close();
				return true;
			}
			
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.getMessage());
			return false;
		}
		
		
	}
	
	/**
	 * 
	 * @param c
	 * @param path 父路径
	 * @param file :文件夹名或者文件名
	 * @param type :1-文件夹,2-文件
	 */
	public static void deleteFTPFile(FTPConnection c,String path,String file,int type){
		FTPClient ftp = new FTPClient();
		try {
			ftp.connect(c.getIp(), c.getPort()); // IP地址和端口 
			boolean bool = ftp.login(c.getUsername(),c.getPassword()); // 用户名和密码,匿名登陆的话用户名为anonymous,密码为非空字符串
			if (!bool) {
				throw new Exception("username or password not correct!");
			}
			System.out.print(ftp.getReplyString());
			int reply = ftp.getReplyCode();
			
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				throw new Exception("FTP server refused connection.");
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
			ftp.changeWorkingDirectory(c.getDirectory());
			
			if (StringUtil.toString(path, null)!=null) {
				String[]ps = path.split("/");
				for (String p : ps) {
					String[]arr = ftp.listNames();
					List<String> list = Arrays.asList(arr);
					if (!list.contains(p)) {
						ftp.makeDirectory(p);
					}
					ftp.changeWorkingDirectory(p);
				}
			}
			if (type==1) {
				deleteRecursive(ftp, file);
			}else if (type==2) {
				ftp.deleteFile(file);
			}
			ftp.logout();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (ftp.isConnected()) {  
				try {  
					ftp.disconnect();  
				} catch (Exception e) {  
					e.printStackTrace();  
				}  
			}  
		}
		
	}
	/**
	 * 递归删除所有文件
	 * @param ftp
	 * @param file
	 * @throws IOException
	 */
	public static void deleteRecursive(FTPClient ftp,String file) throws IOException{
		ftp.changeWorkingDirectory(file);
		FTPFile[]fs = ftp.listFiles();
		for (FTPFile f : fs) {
			ftp.deleteFile(f.getName());
		}
		FTPFile[]ds = ftp.listDirectories();
		for (FTPFile d : ds) {
			deleteRecursive(ftp,d.getName());
		}
		ftp.changeToParentDirectory();
		ftp.removeDirectory(file);
	}

 

 

public class FTPConnection {

	private String ip;
	private int port;
	private String username;
	private String password;
	private String directory;
}

 

 

你可能感兴趣的:(java,ftp)