2012-12-03 8 views
7

का उपयोग कर एक एसएफटीपी सर्वर से फ़ाइलों को डाउनलोड करना मैं सर्वर से फ़ाइलों को डाउनलोड करने के लिए जेएसएच का उपयोग कर रहा हूं, नीचे मेरा कोड।जेएसएच

public static void downloadFile(TpcCredentialsDTO dto) { 
     logger.trace("Entering downloadFile() method"); 

    Session session = null; 
    Channel channel = null; 
    ChannelSftp channelSftp = null; 
    boolean success = false; 

    try { 
     JSch jsch = new JSch(); 
     session = jsch.getSession(dto.getUsername(), dto.getHost(), 
       dto.getPort()); 
     session.setPassword(dto.getPassword()); 

     session.setConfig("StrictHostKeyChecking", "no"); 
     session.connect(); 
     logger.info("Connected to " + dto.getHost() + "."); 

     channel = session.openChannel("sftp"); 
     channel.connect(); 
     channelSftp = (ChannelSftp) channel; 

     List<String> filesToDownload = getFilesToDownload(dto,channelSftp); 

     if (!filesToDownload.isEmpty()) { 
      for (String fileDownloadName : filesToDownload) { 
       success = false; 
       OutputStream output = new FileOutputStream(
        "C:\Download\BLT_03112012"); 

       channelSftp.get("BLT_03112012",output); 
       success = true; 
       if (success) 
        logger.info(ServerConstants.DOWNLOAD_SUCCESS_MSG 
            + fileDownloadName); 
       output.close(); 
      } 

     }else { 
      logger.info(ServerConstants.NO_FILES_TO_DOWNLOAD 
        + ServerUtils.getDateTime()); 
      success = true; 
     } 

    } catch (JSchException ex) { 
     logger.error(ServerConstants.SFTP_REFUSED_CONNECTION, ex); 
    } catch (SftpException ex) { 
     logger.error(ServerConstants.FILE_DOWNLOAD_FAILED, ex); 
    } catch (IOException ex) { 
     logger.error(ServerConstants.FILE_NOT_FOUND, ex); 
    }catch (Exception ex) { 
     logger.error(ServerConstants.ERROR, ex); 
    }finally { 
     if (channelSftp.isConnected()) { 
      try { 
       session.disconnect(); 
       channel.disconnect(); 
       channelSftp.quit(); 
       logger.info(ServerConstants.FTP_DISCONNECT); 
      } catch (Exception ioe) { 
       logger.error(ServerConstants.FTP_NOT_DISCONNECT, ioe); 
      } 
     } 
    } 
    logger.trace("Exiting downloadFile() method"); 
} 


sftpChannel.get(filename, outputstream) is throwing an error. 
2: File not found 
     at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2629) 
     at com.jcraft.jsch.ChannelSftp._get(ChannelSftp.java:977) 
     at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:946) 
     at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:924) 
     at za.co.tpc.sftpserver.SftpConnection.downloadFile(SftpConnection.java:72) 
     at za.co.tpc.server.execute.FtpMtn.main(FtpMtn.java:44) 

एक ही कोड पाठ दस्तावेज़ फ़ाइल प्रकारों डाउनलोड करता है लेकिन 'फ़ाइल' फ़ाइल प्रकार के लिए विफल रहता है

उत्तर

8

स्ट्रीम के बजाय रास्तों का उपयोग कर प्रयास करें:

String destPath = "filename.txt";   

if (!filesToDownload.isEmpty()) { 
      for (String fileDownloadName : filesToDownload) { 
       success = false; 
        sftpChannel.get(fileDownloadName , destPath); 

संपादित करते हैं आप फ़ाइल और स्ट्रीम का उपयोग करना चाहते हैं इस उदाहरण की जांच करें:

http://kodehelp.com/java-program-for-downloading-file-from-sftp-server/

+0

हाय कार्लोस उत्तर के लिए धन्यवाद। जब destPath एक txt फ़ाइल है तो यह ठीक काम करता है लेकिन फ़ाइल प्रकार एक फ़ाइल होने पर यह विफल हो जाता है। – FaithN

+0

अद्यतन उत्तर। –

+0

आपके समाधान कार्लोस के लिए धन्यवाद, अब मुझे सॉर्ट किया गया है :-)। – FaithN

2

कृपया फ़ाइल अपलोड और डाउनलोड कार्यक्षमताओं जिसमें नीचे कोड नमूने में पाते हैं। कृपया उन गुणों से प्रासंगिक विवरण खींचें जहां कभी भी लेफ्टिनेंट में चिह्नित स्ट्रिंग; sftp.user.name gt;। फ़ाइल डाउनलोड होने के बाद मैं फ़ाइल को हटा रहा हूं, आप इसे अपनी आवश्यकता के अनुसार प्राप्त कर सकते हैं।

घटना और स्थान मापदंडों मैं के रूप में डाउनलोड कार्यक्षमता का हिस्सा फ़ाइल (रों) फिल्टर करने के लिए है कि क्या जोड़ लिया है; आप पैरामीटर को पारित कर सकते हैं जैसा कि आपको चाहिए।

प्रॉक्सी सेट करने के लिए एक चेक रखा है जिसका उपयोग आवश्यकता के आधार पर किया जा सकता है।

package com.util; 

import com.jcraft.jsch.Channel; 
import com.jcraft.jsch.ChannelSftp; 
import com.jcraft.jsch.JSch; 
import com.jcraft.jsch.ProxyHTTP; 
import com.jcraft.jsch.Session; 
import com.jcraft.jsch.SftpException; 
import java.io.File; 
import java.io.FileInputStream; 
import java.util.Date; 
import java.util.Properties; 
import java.util.Vector; 

/** 
* 
* @author Dinesh.Lomte 
*/ 
public class SftpUtil { 

    /** 
    * 
    * @param fileName 
    * @throws Exception 
    */ 
    public static void upload(String fileName) 
    throws Exception { 

     String method = "upload(String fileName)"; 
     Session session = null; 
     Channel channel = null; 
     ChannelSftp channelSftp = null; 
     try { 
      // Creating and instantiating the jsch specific instance 
      JSch jsch = new JSch(); 
      // Fetching and setting the parameters like: user name, host and port 
      // from the properties file 
      session = jsch.getSession("<sftp.user.name>", 
        "<sftp.host>", 
        Integer.valueOf("<sftp.port>")); 
      // Fetching and setting the password as configured in properties files 
      session.setPassword("<sftp.user.password>"); 
      // Setting the configuration specific properties 
      Properties config = new Properties(); 
      config.put("StrictHostKeyChecking", "no"); 
      session.setConfig(config);    
      // Validating if proxy is enabled to access the sftp 
      isSftpProxyEnabled(session); 
      // Execution start time 
      long lStartTime = new Date().getTime(); 
      System.out.println("Connecting to the sftp..."); 
      // Connecting to the sftp 
      session.connect(); 
      System.out.println("Connected to the sftp.");    
      // Execution end time 
      long lEndTime = new Date().getTime(); 
      System.out.println("---------------------------------------------"); 
      System.out.println("Connected to SFTP in : " + (lEndTime - lStartTime)); 
      // Setting the channel type as sftp 
      channel = session.openChannel("sftp"); 
      // Establishing the connection 
      channel.connect(); 
      channelSftp = (ChannelSftp) channel; 
      // Setting the folder location of the external system as configured 
      channelSftp.cd("<sftp.output.folder.url>"); 
      // Creating the file instance 
      File file = new File(fileName); 
      // Creating an fileInputStream instance 
      FileInputStream fileInputStream = new FileInputStream(file); 
      // Transfering the file from it source to destination location via sftp 
      channelSftp.put(fileInputStream, file.getName()); 
      // Closing the fileInputStream instance 
      fileInputStream.close(); 
      // De-allocating the fileInputStream instance memory by assigning null 
      fileInputStream = null; 
     } catch (Exception exception) { 
      throw exception; 
     } finally { 
      // Validating if channel sftp is not null to exit 
      if (channelSftp != null) { 
       channelSftp.exit(); 
      } 
      // Validating if channel is not null to disconnect 
      if (channel != null) { 
       channel.disconnect(); 
      } 
      // Validating if session instance is not null to disconnect 
      if (session != null) { 
       session.disconnect(); 
      } 
     } 
    } 

    /** 
    * 
    * @param session 
    */ 
    private static void isSftpProxyEnabled(Session session) { 
     // Fetching the sftp proxy flag set as part of the properties file 
     boolean isSftpProxyEnabled = Boolean.valueOf("<sftp.proxy.enable>"); 
     // Validating if proxy is enabled to access the sftp 
     if (isSftpProxyEnabled) { 
      // Setting host and port of the proxy to access the SFTP 
      session.setProxy(new ProxyHTTP("<sftp.proxy.host>", 
        Integer.valueOf("<sftp.proxy.port>"); 
     } 
     System.out.println("Proxy status: " + isSftpProxyEnabled); 
    } 

    /** 
    * 
    * @param folder 
    * @param event 
    * @param locale 
    */ 
    public static void download(String folder, String event, String locale) { 

     String method = "download(String folder, String event, String locale)"; 
     Session session = null; 
     Channel channel = null; 
     ChannelSftp channelSftp = null; 
     try { 
      // Creating and instantiating the jsch specific instance 
      JSch jsch = new JSch(); 
      // Fetching and setting the parameters like: user name, host and port 
      // from the properties file 
      session = jsch.getSession("<sftp.user.name>", 
        "<sftp.host>", 
        Integer.valueOf("<sftp.port>")); 
      // Fetching and setting the password as configured in properties files 
      session.setPassword("<sftp.user.password>"); 
      // Setting the configuration specific properties 
      Properties config = new Properties(); 
      config.put("StrictHostKeyChecking", "no"); 
      session.setConfig(config);    
      // Validating if proxy is enabled to access the sftp 
      isSftpProxyEnabled(session); 
      // Execution start time 
      long lStartTime = new Date().getTime(); 
      System.out.println("Connecting to the sftp..."); 
      // Connecting to the sftp 
      session.connect(); 
      System.out.println("Connected to the sftp.");    
      // Execution end time 
      long lEndTime = new Date().getTime(); 
      System.out.println("---------------------------------------------"); 
      System.out.println("Connected to SFTP in : " + (lEndTime - lStartTime)); 
      // Setting the channel type as sftp 
      channel = session.openChannel(SFTP); 
      // Establishing the connection 
      channel.connect(); 
      channelSftp = (ChannelSftp) channel; 
      try { 
       // Setting the folder location of the external system as configured 
       // to download the file from 
       channelSftp.cd("<sftp.input.folder.url>"); 
      } catch (SftpException sftpException) { 
       System.out.println("Failed to change the directory in sftp.");     
      } 
      // Listing all the .csv file(s) specific to the source system, event type (download) and locale code 
      Vector<ChannelSftp.LsEntry> lsEntries = channelSftp.ls(
        new StringBuilder("*").append("<sys.code>").append("*").append(event) 
        .append("*").append(locale).append("*").append(".csv").toString()); 
      // Validating if files exist to process the request further 
      if (lsEntries.isEmpty()) { 
       System.out.println("No file exist in the specified sftp folder location."); 
      } 
      // Iterating the list of entries to download the file(s) from the sftp 
      for (ChannelSftp.LsEntry entry : lsEntries) { 
       try { 
        // Downloading the specified file from the sftp to the specified folder path 
        channelSftp.get(entry.getFilename(), new StringBuilder(folder) 
          .append(File.separator).append(entry.getFilename()).toString()); 
       } catch (SftpException sftpException) { 
        System.out.println("Failed to download the file the sftp folder location.");      
       }     
      } 
      // Iterating the list of entries to delete the file(s) from the sftp 
      for (ChannelSftp.LsEntry entry : lsEntries) { 
       try { 
        // Deleting the specified file from the sftp 
        channelSftp.rm(entry.getFilename()); 
       } catch (SftpException sftpException) { 
        System.out.println("Failed to delete the file from the sftp folder location.");      
       }     
      } 
     } catch (Exception exception) { 
      System.out.println("Failed to download the file(s) from SFTP.");    
     } finally { 
      // Validating if channel sftp is not null to exit 
      if (channelSftp != null) { 
       channelSftp.exit(); 
      } 
      // Validating if channel is not null to disconnect 
      if (channel != null) { 
       channel.disconnect(); 
      } 
      // Validating if session instance is not null to disconnect 
      if (session != null) { 
       session.disconnect(); 
      } 
     } 
    } 
} 
0

मैं इस तरह से तय:

Vector<ChannelSftp.LsEntry> files = sftp.ls(remotePath); 
String remotePath = properties.getFtpPath(); 
Vector<ChannelSftp.LsEntry> files = sftp.ls(remotePath); 

for (ChannelSftp.LsEntry entry : files) { 

    InputStream stream = sftp.get(remotePath + "/" + entry.getFilename()); 
    // Your business code here 

} 

कहाँ remotePath दूरस्थ SFTP फ़ोल्डर का नाम है।

संबंधित मुद्दे