?
? ? 远程写FTP文件和文件夹,jar包commons-net-3.3.jar
?
?
class="java" name="code">public static boolean writeFTPFiles(FTPConnection c,List<File> files){ 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()); // 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(); } } } } public static boolean writeFTPDirectory(FTPConnection c,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()); // 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(); } } } } public static void copy(File src,File dest){ try { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); int c = -1; while ((c=in.read())!=-1) { out.write(c); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
?
?
public class FTPConnection { private String ip; private int port; private String username; private String password; private String directory; }
?
?