从SFTP网址下载文件

时间:2018-11-16 15:38:50

标签: java io bufferedinputstream

我正在编写一个从SFT URL下载文件的程序

  

sftp://demo.wftpserver.com:2222 / upload / 10MB.zip

但是当我在stackoverflow上读到多篇文章时,java URL类不支持SFTP。

问题是我写了一个通用的URL下载器,可以从所有其他协议下载文件,但是只有sftp是问题。

无论如何,我可以使用URL类本身来下载文件,或者如果我不得不使用其他方式来做到这一点,我可以使用它来从所有来源下载文件。

我正在使用的程序

try
{
    bis = new BufferedInputStream(url.openStream());
    String fileName = DownloadSourceUtils.getUniqueFileName(DownloadSourceConstants.DOWNLOAD_LOCALTION, url.getFile());

    File directory = new File(DownloadSourceConstants.DOWNLOAD_LOCALTION);
    if (! directory.exists()){
        directory.mkdir();
        // If you require it to make the entire directory path including parents,
        // use directory.mkdirs(); here instead.
    }

    fos = new FileOutputStream(DownloadSourceConstants.DOWNLOAD_LOCALTION+File.separator+fileName);

    byte dataBuffer[] = new byte[1024];
    int bytesRead;
    while ((bytesRead = bis.read(dataBuffer, 0, 1024)) != -1) 
    {
        fos.write(dataBuffer, 0, bytesRead);
    }
    fos.flush();
    output = url + " downloaded successfully";
    return output;
} 
catch (IOException e)
{
    output = e.getMessage();
    return output;
}
finally
{
    if(bis != null)
        bis.close();
    if(fos != null)
        fos.close();
}

0 个答案:

没有答案
相关问题