2017-09-14 62 views
0

我正在使用JSch程序上傳文件並將其下載到我的SFTP服務器。當我下載文件時,該文件包含垃圾值。包含垃圾值的JSch SFTP文件下載

下面是我寫的代碼:

public ChannelSftp createSession(String sftpUserName, String sftpHost, int sftpPort) { 
    JSch jsch = new JSch(); 
    Channel channel = null; 
    ChannelSftp c = null; 
    String privateKey = "~/.exec/id_rsa"; 

    try { 
     if (session == null) { 
      session = jsch.getSession(sftpUserName, sftpHost, sftpPort); 
      //session.setPassword(sftpPassword); 
      jsch.addIdentity(privateKey); 
      session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password"); 
      java.util.Properties config = new java.util.Properties(); 
      config.put("StrictHostKeyChecking", "no"); 
      session.setConfig(config); 
      session.connect(); 
     } 
     channel = session.openChannel("sftp"); 
     channel.connect(); 
     c = (ChannelSftp) channel; 

    } catch (Exception e) { 
     e.printStackTrace(); 

    } 
    return c; 
} 
public Integer downloadFile(ChannelSftp channelSftp, String FileToBeCopied, String folderPath) { 
    int fileDownloaded = -1; 

    try { 

     //channelSftp.cd(folderPath); 
     OutputStream output = new FileOutputStream("/Users/" + System.getProperty("user.name") + "/Downloads/" + FileToBeCopied); 
     channelSftp.setFilenameEncoding("UTF-8"); 
     channelSftp.get(FileToBeCopied, output); 

     fileDownloaded = 0; 
    } catch (FileNotFoundException e) { 
     fileDownloaded = 1; 
     e.printStackTrace(); 
    } catch (SftpException e) { 
     fileDownloaded = 2; 
     e.printStackTrace(); 
    } catch (Exception e) { 
     fileDownloaded = 3; 

    } 
    return fileDownloaded; 
} 
public boolean uploadFiles(ChannelSftp channelSftp, String workingFile, String ftpRemoteDefaultDirectory, String workingDirectory) { 
    boolean flag = false; 
    if (workingFile != null) { 
     if (!workingFile.equalsIgnoreCase("")) { 
      try { 

       channelSftp.cd(ftpRemoteDefaultDirectory); 
       try { 
        File f = new File(workingDirectory + workingFile); 
        //channelSftp.setFilenameEncoding("UTF-8"); 
        channelSftp.put(new FileInputStream(f), f.getName()); 
        flag = true; 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       destroySession(channelSftp); 
      } catch (Exception e) { 

       e.printStackTrace(); 
      } 
     } 
    } 
    return flag; 
} 

我使用MAC。當我在網上查詢時,有人提到OutputStream將使用「UTF-8」對文件進行編碼,我們不必再做。

+0

您確定SFTP服務器上的文件實際上是UTF-8編碼嗎? –

+0

是的,它是在UTF-8編碼 – user2727493

+0

如何檢查文件是否使用UTF-8編碼? – user2727493

回答

0

我不確定你從哪裏得到了OutputStream轉換爲UTF-8的信息。沒有OutputStream這樣做,這就是OutputStreamWriter的用途。另外OutputStream是一個抽象類,所以當你持有一個實例時,你只知道它是一個OutputStream,你只是不知道流對數據做了什麼。在您的代碼中,您使用FileOutputStream進行讀取,FileInputStream進行讀取,因此在下載或上傳的所有數據中都不應該進行轉換。

因此,如果數據看起來不對,那麼原始數據似乎不是UTF-8編碼。

順便說一句:channelSftp.setFilenameEncoding("UTF-8");與數據的字符集/編碼無關。如方法名稱所示,這將控制如何對文件名進行編碼,因此如果它包含非ASCII字符,則需要在下載和上載時設置它,以確保它們不會顯示損壞。