ftp/sftp概念及搭建
ftp是一种文件传输协议,让客户端和服务端能够互相传递文件,图片等数据;方便快捷;
sftp是ssh file transfer protocol缩写,也是一种文件传输协议.sftp比ftp安全的多,但传输效率要低的多
搭建:
ftp可以搜索网上教程,很多,在此不过多赘述
创建完成后,通过浏览器就可以访问到内容了;
sftp用freesshd搭建(记得freesshd的安装路径不要有中文,否则各种报错);这个也可以自行百度,解决方法很多;
Java代码
代码如下: import java.io.*; import java.net.SocketException; import java.util.ArrayList; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPReply; public class FTPClientTest { private static String userName; // FTP 登录用户名 private static String password; // FTP 登录密码 private static String ip;// FTP 服务器地址IP地址 private static int port; // FTP 端口 //构造函数初始化 public FTPClientTest(String userName,String password,String ip,int port){ this.userName=userName; this.password=password; this.ip=ip; this.port=port; } public static String getUserName(){ return userName;} public static void setUserName(String userName) {FTPClientTest.userName = userName; } public static String getPassword() {return password;} public static void setPassword(String password){FTPClientTest.password = password;} public static String getIp() { return ip; } public static void setIp(String ip){FTPClientTest.ip = ip;} public static int getPort() {return port; } public static void setPort(int port) {FTPClientTest.port = port;} private static FTPClient ftpClient = null; // FTP 客户端代理 /** * 连接到服务器 * @return true 连接服务器成功,false 连接服务器失败 */ public boolean connectServer() { System.out.println("进行连接"); boolean flag = true; if (ftpClient == null) { int reply; try { System.out.println("初始化连接"); ftpClient = new FTPClient(); String LOCAL_CHARSET = "GBK"; System.out.println("设置IP和端口"); ftpClient.connect(ip, port); System.out.println("设置密码"); ftpClient.login(userName, password); System.out.println("进行连接"); reply = ftpClient.getReplyCode(); ftpClient.setDataTimeout(120000); System.out.println("设置编码操作方式"); if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) // 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK). { LOCAL_CHARSET = "UTF-8"; } System.out.println("设置编码操作方式1"); ftpClient.setControlEncoding(LOCAL_CHARSET); System.out.println("是否连接成功"); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.out.println("FTP 服务拒绝连接!"); flag = false; } } catch (SocketException e) { flag = false; e.printStackTrace(); System.out.println("登录ftp服务器 " + ip + " 失败,连接超时!"); } catch (IOException e) { flag = false; e.printStackTrace(); System.out.println("登录ftp服务器 " + ip + " 失败,FTP服务器无法打开!"); } catch (Exception e) { flag = false; e.printStackTrace(); // System.out.println("登录ftp服务器 " + ip + " 失败,FTP服务器无法打开!"); } } return flag; } /** * 上传文件 * * @param remoteFile 远程文件路径,支持多级目录嵌套 需要保证路径已经存在 并切包含文件重命名 * @param localFile 本地文件名称,绝对路径 * */ public boolean uploadFile(String remoteFile1, File localFile) { boolean flag = false; try { InputStream in = new FileInputStream(localFile); String remote = new String(remoteFile1.getBytes("UTF-8"), "iso-8859-1"); if (ftpClient.storeFile(remote, in)) { flag = true; System.out.println(localFile.getAbsolutePath() + "上传文件成功!"); } else { System.out.println(localFile.getAbsolutePath() + "上传文件失败!"); } in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return flag; } /** * 上传单个文件 * * @param local 本地文件名称,绝对路径 * @param remote 远程文件路径,支持多级目录嵌套 * @return */ public boolean uploadFile(String local, String remote) { boolean flag = true; String remoteFileName = remote; if (remote.contains("/")) { remoteFileName = remote.substring(remote.lastIndexOf("/") + 1); // 创建服务器远程目录结构,创建失败直接返回 if (!CreateDirecroty(remote)) { return false; } } File f = new File(local); if (!uploadFile(remoteFileName, f)) { flag = false; } return flag; } /** * 上传文件夹内的所有文件 * * * @param filename 本地文件夹绝对路径 只能上传文件,子文件夹无法上传 * @param uploadpath 上传到FTP的路径,形式为/或/dir1/dir2/../ * @return true 上传成功,false 上传失败 * @throws IOException */ public ArrayListuploadManyFile(String filename, String uploadpath) { boolean flag = true; ArrayList l = new ArrayList (); StringBuffer strBuf = new StringBuffer(); int n = 0; // 上传失败的文件个数 int m = 0; // 上传成功的文件个数 try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.changeWorkingDirectory("/"); File file = new File(filename); File fileList[] = file.listFiles(); for (File upfile : fileList) { if (!upfile.isDirectory()) { String local = upfile.getCanonicalPath().replaceAll("\\\\", "/"); String temp = upfile.getCanonicalPath(); String a = temp.replace(filename + "\\", ""); String remote = uploadpath.replaceAll("\\\\", "/") + a; flag = uploadFile(local, remote); ftpClient.changeWorkingDirectory("/"); } if (!flag) { n++; strBuf.append(upfile.getName() + ","); System.out.println("文件[" + upfile.getName() + "]上传失败"); } else { m++; } } l.add("失败个数" + n); l.add("成功个数" + m); l.add(strBuf.toString()); } catch (NullPointerException e) { e.printStackTrace(); System.out.println("本地文件上传失败!找不到上传文件!" + e); } catch (Exception e) { e.printStackTrace(); System.out.println("本地文件上传失败!" + e); } return l; } /** * 下载文件 * * @param remoteFileName --服务器上的文件名 * @param localFileName--本地文件名 * @return true 下载成功,false 下载失败 */ public boolean loadFile(String remoteFileName, String localFileName) { boolean flag = true; // 下载文件 BufferedOutputStream buffOut = null; try { buffOut = new BufferedOutputStream(new FileOutputStream(localFileName)); flag = ftpClient.retrieveFile(new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1"), buffOut); } catch (Exception e) { e.printStackTrace(); System.out.println("本地文件下载失败!" + e); } finally { try { if (buffOut != null) buffOut.close(); } catch (Exception e) { e.printStackTrace(); } } return flag; } /** * 删除一个文件 */ public boolean deleteFile(String filename) { boolean flag = true; try { flag = ftpClient.deleteFile(new String(filename.getBytes("UTF-8"), "iso-8859-1")); if (flag) { System.out.println("删除文件" + filename + "成功!"); } else { System.out.println("删除文件" + filename + "成功!"); } } catch (IOException ioe) { ioe.printStackTrace(); } return flag; } /** * 删除空目录 */ public void deleteEmptyDirectory(String pathname) { try { ftpClient.removeDirectory(new String(pathname.getBytes("UTF-8"), "iso-8859-1")); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * 列出Ftp服务器上的所有文件和目录 */ public String[] listRemoteAllFiles() { try { String[] names = ftpClient.listNames(); for (int i = 0; i < names.length; i++) { System.out.println(names[i]); } return names; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 关闭连接 */ public void closeConnect() { try { if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); ftpClient=null; } } catch (Exception e) { e.printStackTrace(); } } /** * 设置传输文件的类型[文本文件或者二进制文件] 1是文本文件 其余 二进制文件 * * @param fileType--BINARY_FILE_TYPE(二进制文件)、ASCII_FILE_TYPE(文本文件) * */ public void setFileType(int fileType1) { try { int a = FTP.BINARY_FILE_TYPE; if (fileType1 == 1) { a = FTP.ASCII_FILE_TYPE; } ftpClient.setFileType(a); } catch (Exception e) { e.printStackTrace(); } } /** * 进入到服务器的某个目录下 * * @param directory */ public boolean changeWorkingDirectory(String directory) { boolean flag = true; try { flag = ftpClient.changeWorkingDirectory(directory); if (flag) { System.out.println("进入文件夹" + directory + " 成功!"); } else { System.out.println("进入文件夹" + directory + " 失败!"); } } catch (IOException ioe) { ioe.printStackTrace(); } return flag; } /** * 返回到上一层目录 */ public void changeToParentDirectory() { try { ftpClient.changeToParentDirectory(); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * 重命名文件 * * @param oldFileName --原文件名 * @param newFileName --新文件名 */ public void renameFile(String oldFileName, String newFileName) { try { System.out.println(oldFileName); System.out.println(newFileName); ftpClient.rename(new String(oldFileName.getBytes("UTF-8"), "iso-8859-1"), new String(newFileName.getBytes("UTF-8"), "iso-8859-1")); } catch (IOException ioe) { ioe.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } } /** * 设置FTP客服端的配置--一般可以不设置 * * @return ftpConfig */ @SuppressWarnings("unused") private FTPClientConfig getFtpConfig() { FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX); ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING); return ftpConfig; } /** * 转码[ISO-8859-1 -> GBK] 不同的平台需要不同的转码 * * @param obj * @return "" */ @SuppressWarnings("unused") private String iso8859togbk(Object obj) { try { if (obj == null) return ""; else return new String(obj.toString().getBytes("iso-8859-1"), "GBK"); } catch (Exception e) { return ""; } } /** * 在服务器上创建一个文件夹 * * @param dir 文件夹名称,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>... */ public boolean makeDirectory(String dir) { boolean flag = true; try { flag = ftpClient.makeDirectory(dir); if (flag) { System.out.println("创建文件夹" + dir + " 成功!"); } else { System.out.println("创建文件夹" + dir + " 失败!"); } } catch (Exception e) { e.printStackTrace(); } return flag; } /** * 递归创建远程服务器目录 * * @param remote 远程服务器文件绝对路径 路径: /Draw1/Point1/GUID1/a.bmp 或者/Draw1/Point1/GUID1/ 最后一级文件夹必须有/否则最后一级文件夹创建不成功 * * @return 目录创建是否成功 * @throws IOException */ public boolean CreateDirecroty(String remote) { boolean success = true; try { String directory = remote.substring(0, remote.lastIndexOf("/") + 1); // 如果远程目录不存在,则递归创建远程服务器目录 if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) { int start = 0; int end = 0; if (directory.startsWith("/")) { start = 1; } else { start = 0; } end = directory.indexOf("/", start); while (true) { String subDirectory; subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1"); if (!changeWorkingDirectory(subDirectory)) { if (makeDirectory(subDirectory)) { changeWorkingDirectory(subDirectory); } else { System.out.println("创建目录[" + subDirectory + "]失败"); System.out.println("创建目录[" + subDirectory + "]失败"); success = false; return success; } } start = end + 1; end = directory.indexOf("/", start); // 检查所有目录是否创建完毕 if (end <= start) { break; } } } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return success; } }
ftp测试代码如下:
public class test { public static void main(String[] args) { FTPClientTest ftp=new FTPClientTest("user", "548", "168.125.256.22", 21); boolean b=ftp.connectServer(); System.out.println(b); System.out.println(ftp.listRemoteAllFiles()); System.out.println(ftp.uploadFile("F:/home/b.txt", "/c.txt")); System.out.println(ftp.loadFile("/a.txt", "F:/home/b.txt")); ftp.closeConnect(); } }
输出结果如下:
成功了;
sftp搭建完成后,也测试下,至于搭建过程,自行百度好啦
看到没,连接成功了;我用我的电脑模拟的;