Java 远程文件对接

开发 后端
本文主要介绍Java 远程文件对接,以下代码即贴即用,第一次发博客,不足之处请大家多多指教!

以下代码即贴即用,***次发博客,不足之处请大家多多指教!

1、配置文件:copyRemoteFile.properties

  1. #  src/dao.properties    
  2. #      这里保存的都是键值对信息    
  3. #  interface name(no packgage) = implementation class  
  4. # 注意:    
  5. #  A:【路径符号】【必须】是【/】【如:D:/home/publish】    
  6. #  B:【键key=值value】对【后面】【绝不允许有空格】【如:REMOTE_HOST_IP=172.77.9.77】   
  7. # REMOTE_HOST_IP  远程机器IP    
  8. # LOGIN_ACCOUNT   远程机器登录名    
  9. # LOGIN_PASSWORD  远程机器登录密码    
  10. # SHARE_DOC_NAME  远程机器共享文件夹名(设置共享后必须授予读写权限)   
  11. # sourcePath      本地路径    
  12. # targetPath      目标路径(真实路径=共享文件夹路径+目标路径)   
  13. REMOTE_HOST_IP=172.77.9.77   
  14. LOGIN_ACCOUNT=77   
  15. LOGIN_PASSWORD=77   
  16. SHARE_DOC_NAME=vfs_home    
  17. sourcePath=D:/home/publish   
  18. targetPath=publish 

2、导入jar包:jcifs-1.3.16.jar

 

 

3、读取配置文件中key对应的value类:RemoteConfigUtil.java

  1. package com.remote;   
  2.     
  3. import java.io.IOException;   
  4. import java.util.Properties;   
  5.     
  6. /**   
  7.  * 读取配置文件中key对应的value   
  8.  * @author JunjieQin   
  9.  */ 
  10. public class RemoteConfigUtil {   
  11.     private String REMOTE_HOST_IP;   
  12.     private String LOGIN_ACCOUNT;   
  13.     private String LOGIN_PASSWORD;   
  14.     private String SHARE_DOC_NAME;   
  15.     private String sourcePath;   
  16.     private String targetPath;   
  17.     
  18.     //无参构造方法   
  19.     public RemoteConfigUtil() {   
  20.         try {   
  21.             // 读取配置文件   
  22.             Properties prop = new Properties();   
  23.             prop.load(this.getClass().getClassLoader().getResourceAsStream("copyRemoteFile.properties"));   
  24.             // 根据 key 获取 value   
  25.             REMOTE_HOST_IP = prop.getProperty("REMOTE_HOST_IP");   
  26.             LOGIN_ACCOUNT = prop.getProperty("LOGIN_ACCOUNT");   
  27.             LOGIN_PASSWORD = prop.getProperty("LOGIN_PASSWORD");   
  28.             SHARE_DOC_NAME = prop.getProperty("SHARE_DOC_NAME");   
  29.             sourcePath = prop.getProperty("sourcePath");   
  30.             targetPath = prop.getProperty("targetPath");   
  31.         } catch (IOException e) {   
  32.             e.printStackTrace();   
  33.         }   
  34.     }   
  35.     public String getLOGIN_ACCOUNT() {   
  36.         return LOGIN_ACCOUNT;   
  37.     }   
  38.     
  39.     public void setLOGIN_ACCOUNT(String login_account) {   
  40.         LOGIN_ACCOUNT = login_account;   
  41.     }   
  42.     
  43.     public String getLOGIN_PASSWORD() {   
  44.         return LOGIN_PASSWORD;   
  45.     }   
  46.     
  47.     public void setLOGIN_PASSWORD(String login_password) {   
  48.         LOGIN_PASSWORD = login_password;   
  49.     }   
  50.     
  51.     public String getREMOTE_HOST_IP() {   
  52.         return REMOTE_HOST_IP;   
  53.     }   
  54.     
  55.     public void setREMOTE_HOST_IP(String remote_host_ip) {   
  56.         REMOTE_HOST_IP = remote_host_ip;   
  57.     }   
  58.     
  59.     public String getSHARE_DOC_NAME() {   
  60.         return SHARE_DOC_NAME;   
  61.     }   
  62.     
  63.     public void setSHARE_DOC_NAME(String share_doc_name) {   
  64.         SHARE_DOC_NAME = share_doc_name;   
  65.     }   
  66.     
  67.     public String getSourcePath() {   
  68.         return sourcePath;   
  69.     }   
  70.     
  71.     public void setSourcePath(String sourcePath) {   
  72.         this.sourcePath = sourcePath;   
  73.     }   
  74.     
  75.     public String getTargetPath() {   
  76.         return targetPath;   
  77.     }   
  78.     
  79.     public void setTargetPath(String targetPath) {   
  80.         this.targetPath = targetPath;   
  81.     }   

4、操作远程共享文件夹类: RemoteFileUtil.java

根据需求选择相应的 Method

  1. package com.remote;   
  2. import java.io.BufferedOutputStream;   
  3. import java.io.BufferedReader;   
  4. import java.io.File;   
  5. import java.io.FileInputStream;   
  6. import java.io.FileNotFoundException;   
  7. import java.io.IOException;   
  8. import java.io.InputStream;   
  9. import java.io.InputStreamReader;   
  10. import java.io.OutputStream;   
  11. import java.net.MalformedURLException;   
  12. import java.net.UnknownHostException;   
  13. import java.util.ArrayList;   
  14. import java.util.List;   
  15.     
  16. import jcifs.smb.SmbException;   
  17. import jcifs.smb.SmbFile;   
  18. import jcifs.smb.SmbFileInputStream;   
  19. import jcifs.smb.SmbFileOutputStream;   
  20.     
  21. /***********************************************   
  22.  *  File Name: RemoteFileUtil.java                
  23.  *  Created by: JunjieQin         
  24.  *  Checked in by:       
  25.  *  Date: 2011-9-6              
  26.  *  Revision: 1.7           
  27.  *  Description:操作远程共享文件夹类   
  28.  *  Amendment History   
  29.  *  Modified Date:2011-9-16            
  30.  *  Modified By:JunjieQin      
  31.  *  Change Description:From local copy files to remote directory   
  32.  *   
  33.  ***********************************************/ 
  34. public class RemoteFileUtil {      
  35.         
  36.     private ArrayList filelist = new ArrayList();   
  37.     RemoteConfigUtil rc = new RemoteConfigUtil();   
  38.     
  39.     private String remoteHostIp;  //远程主机IP      
  40.     private String account;       //登陆账户      
  41.     private String password;      //登陆密码      
  42.     private String shareDocName;  //共享文件夹名称      
  43.            
  44.     /**     
  45.      * 默认构造函数     
  46.      */    
  47.     public RemoteFileUtil(){     
  48.         this.remoteHostIp = rc.getREMOTE_HOST_IP();      
  49.         this.account = rc.getLOGIN_ACCOUNT();      
  50.         this.password = rc.getLOGIN_PASSWORD();      
  51.         this.shareDocName = rc.getSHARE_DOC_NAME();      
  52.     }      
  53.            
  54.     /**     
  55.      * 构造函数     
  56.      * @param remoteHostIp  远程主机Ip     
  57.      * @param account       登陆账户     
  58.      * @param password      登陆密码     
  59.      * @param sharePath     共享文件夹路径     
  60.      */    
  61.     public RemoteFileUtil(String remoteHostIp, String account, String password,String shareDocName) {      
  62.         this.remoteHostIp = remoteHostIp;      
  63.         this.account = account;      
  64.         this.password = password;      
  65.         this.shareDocName = shareDocName;      
  66.     }         
  67.            
  68.     /**     
  69.      * 对远程共享文件进行读取所有行     
  70.      * @param remoteFileName  文件名  说明:参数为共享目录下的相对路径     
  71.      *  若远程文件的路径为:shareDoc\test.txt,则参数为test.txt(其中shareDoc为共享目录名称);     
  72.      *  若远程文件的路径为:shareDoc\doc\text.txt,则参数为doc\text.txt;     
  73.      * @return  文件的所有行     
  74.      */    
  75.     public List<String> readFile(String remoteFileName){      
  76.         SmbFile smbFile = null;      
  77.         BufferedReader reader = null;      
  78.         List<String> resultLines = null;      
  79.         //构建连接字符串,并取得文件连接      
  80.         String conStr = null;      
  81.         conStr = "smb://"+account+":"+password+"@"+remoteHostIp+"/"+shareDocName+"/"+remoteFileName;      
  82.         try {      
  83.             smbFile = new SmbFile(conStr);      
  84.         } catch (MalformedURLException e) {      
  85.             e.printStackTrace();      
  86.         }      
  87.         //创建reader      
  88.         try {      
  89.             reader = new BufferedReader(new InputStreamReader(new SmbFileInputStream(smbFile)));      
  90.         } catch (SmbException e) {      
  91.             e.printStackTrace();      
  92.         } catch (MalformedURLException e) {      
  93.             e.printStackTrace();      
  94.         } catch (UnknownHostException e) {      
  95.             e.printStackTrace();      
  96.         }             
  97.         //循环对文件进行读取      
  98.         String line;      
  99.         try {      
  100.             line = reader.readLine();      
  101.             if(line != null && line.length()>0){      
  102.                 resultLines = new ArrayList<String>();      
  103.             }      
  104.             while (line != null) {      
  105.                 resultLines.add(line);      
  106.                 line = reader.readLine();      
  107.             }      
  108.         } catch (IOException e) {      
  109.             e.printStackTrace();      
  110.         }      
  111.         //返回      
  112.         return resultLines;      
  113.     }      
  114.            
  115.     /**     
  116.      * 对远程共享文件进行写入     
  117.      * @param is                本地文件的输入流     
  118.      * @param remoteFileName    远程文件名    说明:参数为共享目录下的相对路径     
  119.      *  若远程文件的路径为:shareDoc\test.txt,则参数为test.txt(其中shareDoc为共享目录名称);     
  120.      *  若远程文件的路径为:shareDoc\doc\text.txt,则参数为doc\text.txt;     
  121.      * @return       
  122.      */    
  123.     public boolean writeFile(InputStream is,String remoteFileName){      
  124.         SmbFile smbFile = null;      
  125.         OutputStream os = null;      
  126.         byte[] buffer = new byte[1024*8];      
  127.         //构建连接字符串,并取得文件连接      
  128.         String conStr = null;      
  129.         conStr = "smb://"+account+":"+password+"@"+remoteHostIp+"/"+shareDocName+"/"+remoteFileName;      
  130.         try {      
  131.             smbFile = new SmbFile(conStr);      
  132.         } catch (MalformedURLException e) {      
  133.             e.printStackTrace();      
  134.             return false;      
  135.         }      
  136.                
  137.         //获取远程文件输出流并写文件到远程共享文件夹      
  138.         try {      
  139.             os = new BufferedOutputStream(new SmbFileOutputStream(smbFile));      
  140.             while((is.read(buffer))!=-1){      
  141.                 os.write(buffer);             
  142.             }      
  143.         } catch (Exception e) {      
  144.             e.printStackTrace();      
  145.             return false;      
  146.         }       
  147.                
  148.         return true;      
  149.     }      
  150.            
  151.            
  152.     /**     
  153.      * 对远程共享文件进行写入重载     
  154.      * @param localFileName   要写入的本地文件全名     
  155.      * @param remoteFileName  远程文件名    说明:参数为共享目录下的相对路径     
  156.      *  若远程文件的路径为:shareDoc\test.txt,则参数为test.txt(其中shareDoc为共享目录名称);     
  157.      *  若远程文件的路径为:shareDoc\doc\text.txt,则参数为doc\text.txt;     
  158.      * @return     
  159.      */    
  160.     public boolean writeFile(String localFileFullName ,String remoteFileName){      
  161.         try {      
  162.             return writeFile(new FileInputStream(new File(localFileFullName)),remoteFileName);      
  163.         } catch (FileNotFoundException e) {      
  164.             e.printStackTrace();      
  165.             return false;      
  166.         }      
  167.     }      
  168.            
  169.     /**     
  170.      * 对远程共享文件进行写入重载     
  171.      * @param localFileName   要写入的本地文件     
  172.      * @param remoteFileName  远程文件名    说明:参数为共享目录下的相对路径     
  173.      *  若远程文件的路径为:shareDoc\test.txt,则参数为test.txt(其中shareDoc为共享目录名称);     
  174.      *  若远程文件的路径为:shareDoc\doc\text.txt,则参数为doc\text.txt;     
  175.      * @return     
  176.      */    
  177.     public boolean writeFile(File localFile ,String remoteFileName){      
  178.         try {      
  179.             return writeFile(new FileInputStream(localFile),remoteFileName);      
  180.         } catch (FileNotFoundException e) {      
  181.             e.printStackTrace();      
  182.             return false;      
  183.         }      
  184.     }      
  185.     
  186.            
  187.     /**     
  188.      * 对远程共享文件所有文件     
  189.      * @return  所有文件    
  190.      */    
  191.     public List<String> getFiles(){      
  192.         SmbFile smbFile = null;      
  193.         BufferedReader reader = null;      
  194.         List<String> resultLines = new ArrayList();      
  195.         //构建连接字符串,并取得文件连接      
  196.         String conStr = null;      
  197.         conStr = "smb://"+account+":"+password+"@"+remoteHostIp+"/"+shareDocName+"/";      
  198.         try {      
  199.             smbFile = new SmbFile(conStr);      
  200.         } catch (MalformedURLException e) {      
  201.             e.printStackTrace();      
  202.         }      
  203.         //创建reader      
  204.         try {      
  205.           String[] a = smbFile.list();   
  206.           for(int i=0;i<a.length;i++){   
  207.             resultLines.add(a[i]);   
  208.             System.out.println(a[i]);   
  209.           }   
  210.         } catch (SmbException e) {      
  211.             e.printStackTrace();      
  212.         } catch (Exception e) {      
  213.             e.printStackTrace();      
  214.         }             
  215.         //返回      
  216.         return resultLines;      
  217.     }      
  218.         
  219.     /** 在本地为共享计算机创建文件夹    
  220.      * @param remoteUrl 远程计算机路径    
  221.      */    
  222.     public void smbMkDir(String name) {   
  223.         // 注意使用jcifs-1.3.15.jar的时候 操作远程计算机的时候所有类前面须要增加Smb   
  224.         // 创建一个远程文件对象   
  225.         String conStr = "smb://" + account + ":" + password + "@" + remoteHostIp + "/" + shareDocName;   
  226.         SmbFile remoteFile;   
  227.         try {   
  228.             remoteFile = new SmbFile(conStr + "/" + name);   
  229.             if (!remoteFile.exists()) {   
  230.                 remoteFile.mkdir();// 创建远程文件夹   
  231.             }   
  232.         } catch (MalformedURLException e) {   
  233.             e.printStackTrace();   
  234.         } catch (SmbException e) {   
  235.             e.printStackTrace();   
  236.         }   
  237.     }   
  238.         
  239.     /**   
  240.      * 删除文件夹   
  241.      * @param folderPath 共享文件夹下一个文件夹名   
  242.      * @return   
  243.      */ 
  244.     public void delFolder(String folderPath) {   
  245.         //String conStr = "smb://"+LOGIN_ACCOUNT+":"+LOGIN_PASSWORD+"@"+remoteHostIp+"/"+shareDocName;    
  246.         try {   
  247.             delAllFile(folderPath); //删除完里面所有内容   
  248.             String filePath = folderPath;   
  249.             filePath = filePath.toString();   
  250.                 
  251.             SmbFile myFilePath = new SmbFile(filePath);   
  252.             myFilePath.delete(); //删除空文件夹   
  253.         }   
  254.         catch (Exception e) {   
  255.             String message = ("删除文件夹操作出错");   
  256.             System.out.println(message);   
  257.         }   
  258.     }   
  259.         
  260.         
  261.     /**   
  262.      * 删除共享文件夹下一个文件夹名   
  263.      * @param path 共享文件夹下一个文件夹名   
  264.      * @return   
  265.      * @return   
  266.      */ 
  267.     public boolean delAllFile(String path) {   
  268.         boolean bea = false;   
  269.         try {   
  270.             SmbFile file = new SmbFile(path);   
  271.             if (!file.exists()) {   
  272.                 return bea;   
  273.             }   
  274.             if (!file.isDirectory()) {   
  275.                 return bea;   
  276.             }   
  277.             String[] tempList = file.list();   
  278.             SmbFile temp = null;   
  279.             for (int i = 0; i < tempList.length; i++) {   
  280.                 if (path.endsWith("/")) {   
  281.                     temp = new SmbFile(path + tempList[i]);   
  282.                 } else {   
  283.                     temp = new SmbFile(path + "/" + tempList[i]);   
  284.                 }   
  285.                 if (temp.isFile()) {   
  286.                     temp.delete();   
  287.                 }   
  288.                 if (temp.isDirectory()) {   
  289.                     delAllFile(path + "/" + tempList[i] + "/");// 先删除文件夹里面的文件   
  290.                     delFolder(path + "/" + tempList[i] + "/");// 再删除空文件夹   
  291.                     bea = true;   
  292.                 }   
  293.             }   
  294.             return bea;   
  295.         } catch (Exception e) {   
  296.             return bea;   
  297.         }   
  298.     }   
  299.     
  300.         
  301.         
  302.     /**   
  303.      * 复制整个文件夹的内容   
  304.      * @param oldPath 准备拷贝的目录   
  305.      * @param newPath 指定绝对路径的新目录   
  306.      * @return   
  307.      */ 
  308.     public void copyFolder(String oldPath, String newPath) {   
  309.         String conStr = "smb://" + account + ":" + password + "@" + remoteHostIp + "/" + shareDocName;   
  310.         System.err.println(conStr);   
  311.         try {   
  312.             /**   
  313.              * 如果存在文件夹删除文件    
  314.              * SmbFile exittemp = new SmbFile(conStr + "/"+newPath);   
  315.              * if(exittemp.exists()){   
  316.              *      delFolder(conStr+"/"+newPath+"/");    
  317.              * }   
  318.              */ 
  319.             SmbFile exittemps = new SmbFile(conStr + "/" + newPath);   
  320.             if (!exittemps.exists()) {   
  321.                 exittemps.mkdirs(); // 如果文件夹不存在 则建立新文件夹   
  322.             }   
  323.             File a = new File(oldPath);   
  324.             String[] file = a.list();   
  325.             File temp = null;   
  326.             for (int i = 0; i < file.length; i++) {   
  327.                 if (oldPath.endsWith("/")) {   
  328.                     temp = new File(oldPath + file[i]);   
  329.                 } else {   
  330.                     temp = new File(oldPath + "/" + file[i]);   
  331.                 }   
  332.                 if (temp.isFile()) {   
  333.                     if (temp.exists()) {   
  334.                         writeFile(temp, newPath + "/" + file[i]);   
  335.                     }   
  336.                 }   
  337.                 if (temp.isDirectory()) {// 如果是子文件夹   
  338.                     copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);   
  339.                 }   
  340.             }   
  341.     
  342.         } catch (Exception e) {   
  343.             String message = "复制整个文件夹内容操作出错";   
  344.             System.out.println(message);   
  345.         }   
  346.     }   
  347.         
  348.     /**   
  349.      * 复制文件到远程计算机,如果目标路径不存在则创建,反之不创建   
  350.      * @param localFileFullName 本地指定文件路径   
  351.      * @param targetDir 目标路径   
  352.      */ 
  353.     public void copyFileToRemoteDir(String localFileFullName, String targetDir) {   
  354.         System.err.println(localFileFullName + "--" + targetDir);   
  355.         RemoteFileUtil rf = new RemoteFileUtil();   
  356.         InputStream is = null;   
  357.         SmbFile smbFile = null;   
  358.         OutputStream os = null;   
  359.         byte[] buffer = new byte[1024 * 8];   
  360.         // 构建连接字符串,并取得文件连接   
  361.         String conStr = null;   
  362.         conStr = "smb://" + account + ":" + password + "@" + remoteHostIp + "/" + shareDocName + "/" + targetDir;   
  363.         System.err.println(conStr);   
  364.         SmbFile sf;   
  365.         try {   
  366.             sf = new SmbFile("smb://" + account + ":" + password + "@" + remoteHostIp + "/" + shareDocName + "/" + targetDir);   
  367.             if (!sf.exists()) {   
  368.                 // 新建目标目录   
  369.                 sf.mkdirs();   
  370.                 is = new FileInputStream(new File(localFileFullName));   
  371.                 // 获取远程文件输出流并写文件到远程共享文件夹   
  372.                 os = new BufferedOutputStream(new SmbFileOutputStream(smbFile));   
  373.                 while ((is.read(buffer)) != -1) {   
  374.                     os.write(buffer);   
  375.                 }   
  376.             }   
  377.         } catch (Exception e) {   
  378.             System.err.println("提示:复制整个文件夹内容操作出错。");   
  379.         }   
  380.     
  381.         File file = new File(localFileFullName);   
  382.         if (file.isFile()) {   
  383.             File sourceFile = file;     // 源文件   
  384.             File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file.getName());// 目标文件   
  385.             String name = file.getName();// 文件名   
  386.             if (targetDir != null && targetFile != null) {   
  387.                 rf.writeFile(sourceFile, "/" + targetDir + "/" + name); // 复制文件   
  388.             } else if (targetFile != null) {   
  389.                 rf.writeFile(sourceFile, name); // 复制文件   
  390.             }   
  391.         }   
  392.     }   
  393.         
  394.     /**   
  395.      * 循环获取文件夹内所有匹配的文件   
  396.      * @param strPath 路径   
  397.      * @param subStr 匹配字符   
  398.      * @return   
  399.      */ 
  400.     public ArrayList refreshFileList(String strPath, String subStr) {   
  401.         File dir = new File(strPath);   
  402.         File[] files = dir.listFiles();   
  403.         if (files == null)   
  404.             return null;   
  405.         for (int i = 0; i < files.length; i++) {   
  406.             if (!files[i].isDirectory()) {   
  407.                 String strFileName = files[i].getAbsolutePath().toLowerCase();   
  408.                 if (files[i].getName().indexOf(subStr) >= 0) {   
  409.                     filelist.add(files[i].getName());   
  410.                 }   
  411.             }   
  412.         }   
  413.         return filelist;   
  414.     }   
  415.     
  416.     // 测试从本地复制文件到远程目标目录,测试已通过   
  417.     public static void main(String[] args) {   
  418.         RemoteConfigUtil rc = new RemoteConfigUtil();   
  419.         RemoteFileUtil util = new RemoteFileUtil();   
  420.         util.copyFileToRemoteDir(rc.getSourcePath(), rc.getTargetPath());   
  421.     }   

原文链接:http://www.cnblogs.com/77blog/archive/2011/11/05/Java.html

【编辑推荐】

  1. Java生成树结构各点之间最短路径算法
  2. Java编程:数据的截尾与舍入
  3. Java的标准数据流
  4. Java NIO 异步读取网络数据
  5. Java NIO(异步IO)Socket通信例子
责任编辑:林师授 来源: 77cnblogs的博客
相关推荐

2013-12-13 11:04:36

命令scp

2009-06-30 15:19:00

阻塞读取远程文件Java多线程

2012-04-11 11:10:25

JavaRMI

2010-07-22 14:02:44

远程文件服务器加密EFS

2019-02-25 15:36:52

Linux复制文件远程系统

2012-02-07 13:21:37

Java

2011-03-16 14:42:11

屏幕监视

2010-09-14 17:49:14

溢出漏洞

2009-12-09 09:49:40

2013-11-19 20:07:18

远程桌面文件文件传输

2020-07-29 07:40:19

Linux系统Vim

2011-04-13 17:28:21

2014-10-30 18:44:45

畅捷通T+平台

2010-09-17 16:01:55

代码执行漏洞EXE文件

2011-03-25 09:35:07

2009-10-21 14:31:15

漏洞补丁

2010-09-13 17:57:12

执行漏洞

2009-02-19 13:28:08

远程通讯技术及原理Java

2009-01-11 09:59:30

远程服务摩卡远程管理

2017-05-11 16:12:33

SDN云平台OpenStack
点赞
收藏

51CTO技术栈公众号