java共享目录

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;

public class SmbCope2Server implements FtpFileCope{
	  private boolean first =true ;
	  private String responseftpinfo ="";
    public static void main(String[] args){
    	    }

    /** ***  
       * 从smbMachine读取文件并存储到localpath指定的路径  
        *   
       * @param smbMachine  
       *            共享机器的文件,如smb://xxx:[email protected]/myDocument/测试文本.txt,xxx:xxx是共享机器的用户名密码  
       * @param localpath  
        *            本地路径  
     * @return     
      */ 
public static File readFromSmb(String smbMachine,String localpath){
        File localfile=null;
        InputStream bis=null;
        OutputStream bos=null;
        try {
            SmbFile rmifile = new SmbFile(smbMachine);
            if(rmifile==null){
            	return null ;
            }

            String filename=rmifile.getName();
            bis=new BufferedInputStream(new SmbFileInputStream(rmifile));
            localfile=new File(localpath+File.separator+filename);
            bos=new BufferedOutputStream(new FileOutputStream(localfile));
            int length=rmifile.getContentLength();
            byte[] buffer=new byte[length];
            Date date=new Date();
            bis.read(buffer);
            bos.write(buffer);
            Date end=new Date();
            int time= (int) ((end.getTime()-date.getTime())/1000);
            if(time>0)
                System.out.println("用时:"+time+"秒 "+"速度:"+length/time/1024+"kb/秒");            
        } catch (Exception e){
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
            
        }finally{
            try {
                bos.close();
                bis.close();
            } catch (IOException e) {
//                // TODO Auto-generated catch block
                e.printStackTrace();
            }            
        }
        return localfile;
    }
		/**
		 * 
		 * Description: 从本地上传文件到共享目录
		 * 
		 * @Version1.0 Sep 25, 2009 3:49:00 PM
		 * 
		 * @param remoteUrl
		 *            共享文件目录
		 * 
		 * @param localFilePath
		 *            本地文件绝对路径
		 * 
		 */

	public void smbPut(String remoteUrl, String localFilePath) {

		InputStream in = null;
        OutputStream out = null;

		try {
			File localFile = new File(localFilePath);

			String fileName = localFile.getName();
			SmbFile remoteFile = new SmbFile(remoteUrl + "/");
//			System.out.println(remoteFile.getPath().split("@")[1].substring(remoteFile.getPath().split("@")[1].indexOf("/")+1,remoteFile.getPath().split("@")[1].lastIndexOf("/")+1));
			if(!remoteFile.exists())
				remoteFile.mkdirs();
			remoteFile = new SmbFile(remoteUrl + "/" + fileName);
			in = new BufferedInputStream(new FileInputStream(localFile));
            out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));

			byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                out.write(buffer);
                buffer = new byte[1024];

			}

		} catch (Exception e) {

			e.printStackTrace();

		} finally {

			try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
		

public static File readFromSmbList(String smbMachine,String localpath, String replaceString) {
	try {
		SmbFile rmifile = new SmbFile(smbMachine);
		SmbFile [] rmifilelist=rmifile.listFiles();
		
		for(int i=0,n=rmifilelist.length;i<n;i++){
			System.out.println(rmifilelist[i].toString());
			readFromSmb( rmifilelist[i].toString(),localpath);
		}
		
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	
	
	return null;
	
}

    public static boolean removeFile(File file) {
        return file.delete();
    }

	@Override
	public List ftpFile2Server(String ip, int port, String username,
			String password, String[] filepath, String[] filename,
			String ServerIp, int ServerPort, String ServerUsername,
			String ServerPassword, String[] ServerFilepath,
			String[] ServerFilename, String replaceString) {
		// TODO Auto-generated method stub
		List list =null ;
		if(doDownCopy( ip,port , username, password,
				 filepath,filename)){
			list  =  doUpload(ServerIp, ServerPort,
					 ServerUsername,ServerPassword,
					 ServerFilepath, ServerFilename ,filename ,replaceString);
		}
		return list;
	}
	 String filenamenotexit1="";
	 String filenamenotexit2="";
	private List doUpload(String ServerIp,int ServerPort,
			String ServerUsername, String ServerPassword,
			String ServerFilepath [] , String [] ServerFilename,String [] filename ,String replaceString) {
		// TODO Auto-generated method stub
		FtpClientUtil ftpUtil1 = new FtpClientUtil (  ServerIp ,ServerPort,ServerUsername,ServerPassword) ;
    	if(!ftpUtil1.open()){
    		responseftpinfo=ServerIp+"ftp服务器上传时连接失败。请检查Ip端口用户名密码等信息。";
    		return null ;
    	}
		List list = new ArrayList();
		try {	
			List ServerFilenamelist =Arrays.asList(ServerFilename);
			List filenamelist =Arrays.asList(filename);
			
			for(int i=0,n=filenamelist.size();i<n;i++){		
				Map dateMap = new HashMap();
		    	 dateMap.put("productName", ServerFilename[i]);
		    	 dateMap.put("productDate", replaceString);
//		    	 dateMap.put("productInf", replaceString);
		    	 list.add(dateMap);
//                FtpHelper.upload(ServerIp, "21", ServerUsername, ServerPassword, "/ftp_user/"+filenamelist.get(i).toString(), ServerFilepath[i]+"/"+ServerFilenamelist.get(i).toString());
				ftpUtil1.upload("/smb_user/"+filenamelist.get(i).toString(),ServerFilenamelist.get(i).toString(),ServerFilepath[i]);
				filenamenotexit1=filename[i];
				filenamenotexit2=ServerFilename[i];
				
				responseftpinfo=ServerIp+"ftp服务器上传成功.上传后的文件为"+ServerFilenamelist.get(i).toString();
				System.out.println("----"+filenamenotexit1+"---"+ServerFilepath[i]+"/"+filenamenotexit2);
			}
	} catch (Exception e) {
			System.out.println(filenamenotexit1+ServerFilepath+filenamenotexit2);
			responseftpinfo=ServerIp+"ftp服务器上传文件时失败,上传的路径可能有误(应该为全路径)。";
			e.printStackTrace();
		}finally{
			if(ftpUtil1!=null){
				ftpUtil1.close();
			}
		}
		return list;
	}
	String	filenamenotexit =""  ;
	private boolean doDownCopy(String ip, int port, String username,
			String password, String[] filepath, String[] filename) {
		// TODO Auto-generated method stub
        boolean down = false ;
//        String smbMachine="smb://administrator:pe01AT&*(@10.28.16.28/public/detu/";
//    	FtpClientUtil ftpUtil = new FtpClientUtil ( ip ,port,username,password) ;
//    	if(!ftpUtil.open()){
//    		responseftpinfo=ip+"ftp服务器下载时连接失败。请检查Ip端口用户名密码等信息。";
//    		return false ;
//    	}
//	    
	try {
			
			File file1 =new File("/smb_user/");
			if(!file1.exists())
			 file1.mkdirs();
			for(int i=0 ; i<filename.length;i++){
				  String smbMachine="smb://"+username+":"+password+"@"+ip+filepath[i]+"/"+filename[i];
//				ftpUtil.download(filepath[i]+"/"+filename[i],"/ftp_user/"+filename[i]);
				  readFromSmb( smbMachine, "/smb_user/");
				filenamenotexit=filename[i];
				down = true ;
			}
			first=false;
			responseftpinfo=ip+"ftp服务器下载成功";
		} catch (Exception e) {
			System.out.println("----数据库录入的文件在服务器上不存在---该路径和文件"+filepath+"/"+filenamenotexit+"------");
//			e.printStackTrace();
			down =false ;
			responseftpinfo=ip+"ftp服务器下载失败"+"----数据库录入的文件在服务器上不存在---该路径和文件"+filepath+"/"+filenamenotexit+"------";
		}finally{
			
		}
		return down ;
	}

	@Override
	public List ftpFile2Server(String ip, int port, String username,
			String password, String[] filepath, String[] filename,
			String ServerIp, int ServerPort, String ServerUsername,
			String ServerPassword, String[] ServerFilepath,
			String[] ServerFilename, String[] replaceString) {
		// TODO Auto-generated method stub
		doDownCopyfirst( ip,port , username, password,
				 filepath,filename,replaceString);
	  List list =  doUploadfirst(ServerIp, ServerPort,
				 ServerUsername,ServerPassword,
				 ServerFilepath, ServerFilename ,filename,replaceString);
	return list;
	}

	private List doUploadfirst( String ServerIp,int ServerPort,
			String ServerUsername, String ServerPassword,
			String ServerFilepath [] , String [] ServerFilename,String [] filename, String replaceString []) {
		// TODO Auto-generated method stub
		FtpClientUtil ftpUtil1;
	   	  
		List datelist  = new ArrayList ();
		for(int i=0 ; i<filename.length;i++){
			
			 File filefirst= new File("/smb_temp_first_down/"+filename[i].replace(replaceString[i], "")+"/");
		     File filefir[]=filefirst.listFiles();
		     
		        int startIndex =filename[i].indexOf(replaceString[i]);
				int endIndex =filename[i].indexOf(replaceString[i]);
				int startIndex1 =ServerFilename[i].indexOf(replaceString[i]);
				int endIndex1 =ServerFilename[i].indexOf(replaceString[i]);
				  
		     for(int j=0;j<filefir.length;j++){
		    	 ftpUtil1 = new FtpClientUtil (  ServerIp ,ServerPort,ServerUsername,ServerPassword) ;
		    	 if(!ftpUtil1.open()){
		     		responseftpinfo=ServerIp+"ftp服务器上传时连接服务器失败。请检查Ip端口用户名密码等信息。";
		     		return null ;
		     	}
		    	 try {
		    		 String romtfilename = ServerFilename[i].substring(0,startIndex1)+filefir[j].getName().substring( startIndex,startIndex+replaceString[i].length())
                        +ServerFilename[i].substring(startIndex1+replaceString[i].length());
			    	 ftpUtil1.upload("/smb_temp_first_down/"+filename[i].replace(replaceString[i],"")+"/"+ filefir[j].getName(),romtfilename,ServerFilepath[i]);
			    	 Map dateMap = new HashMap();
			    	 dateMap.put("productName", romtfilename);
			    	 dateMap.put("productDate", filefir[j].getName().substring( startIndex,startIndex+replaceString[i].length()));
			    	 datelist.add(dateMap);
			    	 System.out.println("/smb_temp_first_down/"+ romtfilename+ filefir[j].getName().substring( startIndex,startIndex+replaceString[i].length())+"=---------"+filename[i].replace(replaceString[i],"")+"/"+filefir[j].getName()+ServerFilepath[i]+"/"+filefir[j].getName());
			    	
		     }catch (Exception e) {
					System.out.println(filenamenotexit1+ServerFilepath+filenamenotexit2);
					 responseftpinfo=ServerIp+"ftp服务器上传失败。路径或文件名有误。原文件名是"+filefir[j].getName() ;
					e.printStackTrace();
				}finally{
					if(ftpUtil1!=null){
						ftpUtil1.close();
					}
				}
				 responseftpinfo=ServerIp+"ftp服务器图片上传成功。上传了"+filefir.length+"个图片";
			}
		     
		}
		File filelocal= new File("/smb_temp_first_down/");
		if(filelocal.exists())
			this.deleteFile(filelocal);
		return datelist;
	}

	private boolean doDownCopyfirst(String ip, int port, String username,
			String password, String[] filepath, String[] filename,
			String[] replaceString) {
		 File file2 =new File("/smb_temp_first_down/");
		 if(!file2.exists())
		 file2.mkdirs();
//		 FtpClientUtil ftpUtil = new FtpClientUtil ( ip ,port,username,password) ;
//		 if(!ftpUtil.open()){
//	    		responseftpinfo=ip+"ftp服务器下载时连接失败。请检查Ip端口用户名密码等信息。";
//	    		return false ;
//	    	}
	 try {	
		for(int i=0 ; i<filename.length;i++){
			  String smbMachine="smb://"+username+":"+password+"@"+ip+filepath[i]+"/";
			File file3 =new File("/smb_temp_first_down/"+filename[i].replace(replaceString[i], "")+"/");
			 if(!file3.exists())
			 file3.mkdirs();
			
//			System.out.println(ftpUtil.cd(filepath[i]+"/"));
//			List filelist =ftpUtil.getFileNameList(".");
			SmbFile rmifile = new SmbFile(smbMachine);
			SmbFile [] rmifilelist=rmifile.listFiles();
			List filelist =java.util.Arrays.asList(rmifilelist);
			int startIndex =filename[i].indexOf(replaceString[i]);
    		int endIndex =filename[i].indexOf(replaceString[i]);
			if(startIndex==-1){
				continue ;
			}
			SimpleDateFormat dateformat1=new SimpleDateFormat(replaceString[i]);
			  

		        for(int j=0 ; j<filelist.size();j++){
		        	
		        	if(!((filelist.get(j).toString().substring(filelist.get(j).toString().lastIndexOf("/")+1).length())==filename[i].length()))
		        	{
		        		continue;// ==filename[i].length()
		        	}
		        boolean date =false;
		             try {
		            	 System.out.println(filelist.get(j).toString().substring(filelist.get(j).toString().lastIndexOf("/")+1).substring(startIndex));
		            		Date a1=dateformat1.parse(( filelist.get(j).toString().substring(filelist.get(j).toString().lastIndexOf("/")+1).substring( startIndex,startIndex+replaceString[i].length())));
		            		 date =true;
		        	} catch (ParseException e) {
		        		// TODO Auto-generated catch block
		        		continue;
		        	}   
		        	if( date&&filename[i].replace(replaceString[i], "").equals(filelist.get(j).toString().substring(filelist.get(j).toString().lastIndexOf("/")+1).substring(0, startIndex)+filelist.get(j).toString().substring(filelist.get(j).toString().lastIndexOf("/")+1).substring(endIndex+replaceString[i].length()))){
				    	  System.out.println(filepath[i]+"/"+filelist.get(j).toString().substring(filelist.get(j).toString().lastIndexOf("/"))+"-----"+"/ftp_temp_first_down/"+filename[i].replace(replaceString[i], "")+"/"+filelist.get(j).toString());
//				    	  ftpUtil.download(filepath[i]+"/"+filelist.get(j).toString(),"/ftp_temp_first_down/"+filename[i].replace(replaceString[i], "")+"/"+filelist.get(j).toString());
				    	  readFromSmb( filelist.get(j).toString(),"/smb_temp_first_down/"+filename[i].replace(replaceString[i], "")+"/"); 
		        	}
		        	 }
		    	}
		responseftpinfo=ip+"ftp服务器下载成功";
		} catch (Exception e) {
			System.out.println("----数据库录入的文件在服务器上不存在---该路径和文件"+filepath.toString()+"/"+filenamenotexit+"------");
			responseftpinfo=ip+"ftp服务器下载失败"+"----数据库录入的文件在服务器上不存在---该路径和文件"+filepath.toString()+"/"+filenamenotexit+"------";
			e.printStackTrace();
		}finally{
//			if(ftpUtil!=null){
//				ftpUtil.close();
//			}
		}
	return true;
		
	}
	private void deleteFile(File file){ 
		   if(file.exists()){ 
		    if(file.isFile()){ 
		     file.delete(); 
		    }else if(file.isDirectory()){ 
		     File files[] = file.listFiles(); 
		     for(int i=0;i<files.length;i++){ 
		      this.deleteFile(files[i]); 
		      System.out.println("删除本地临时的文件!"+files[i].getName()+'\n');
		     } 
		    } 
		    file.delete(); 
		   }else{ 
		    System.out.println("所删除的文件不存在!"+'\n'); 
		   } 
		}
	@Override
	public List ftpFile2Server(String ip, int port, String username,
			String password, String filepath, String filename, String ServerIp,
			int ServerPort, String ServerUsername, String ServerPassword,
			String ServerFilepath, String ServerFilename, String replaceString) {
		// TODO Auto-generated method stub
		String [] str= new String[1];
    	String [] str1= new String[1];
        String [] str2= new String[1];
    	String [] str3= new String[1];
    	String [] str4= new String[1];
    	str [0]=filepath;
    	str1 [0]=filename;
    	str2 [0]=ServerFilepath;
 	    str3 [0]=ServerFilename;
        str4 [0]=replaceString;
        
     return    ftpFile2Server( ip,  port,  username,
    			 password,  str, str1,
    			ServerIp, ServerPort,  ServerUsername,
    			 ServerPassword,  str2,
    			 str3,  str4);
	}

	@Override
	public List ftpFile2ServerOne(String ip, int port, String username,
			String password, String filepath, String filename, String ServerIp,
			int ServerPort, String ServerUsername, String ServerPassword,
			String ServerFilepath, String ServerFilename, String replaceString) {
		// TODO Auto-generated method stub
		String [] str= new String[1];
    	String [] str1= new String[1];
        String [] str2= new String[1];
    	String [] str3= new String[1];
    	
    	str [0]=filepath;
    	str1 [0]=filename;
    	str2 [0]=ServerFilepath;
 	    str3 [0]=ServerFilename;
        
        
     return    ftpFile2Server( ip,  port,  username,
    			 password,  str, str1,
    			ServerIp, ServerPort,  ServerUsername,
    			 ServerPassword,  str2,
    			 str3,  replaceString);
	}

	@Override
	public String getResponseftpinfo() {
		// TODO Auto-generated method stub
		return responseftpinfo;
	}
}

猜你喜欢

转载自359863987.iteye.com/blog/1140238