No Data

java ftp文件下载

原创  作者:斩雪碎光阴  发布于:2022年10月08日  阅读量:321
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
  分类:  标签:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
/**
 * ftp下载文件
 */
class Download {
    private static final int BUFFER_SIZE = 4096;

    public static void main(String args[]) { // this is a function
        long startTime = System.currentTimeMillis();
        //ftp://账号:密码@IP地址/文件路径
        String ftpUrl = "ftp://xxx:xxx@xxx.xxx.xxx.xxx/xxx/xxx.jpg";
        //文件路径
        String savePath = "D:\\资料\\xxx.jpg";
        File dir=new File(savePath.substring(0,savePath.lastIndexOf("/")));
        if(!dir.exists()){
            dir .mkdirs();
        }
        File fie=new File(savePath);
        System.out.println("Connecting to FTP server");
        try {
            URL url = new URL(ftpUrl);
            URLConnection conn = url.openConnection();
            InputStream inputStream = conn.getInputStream();
            long filesize = conn.getContentLength();
            System.out.println("Size of the file to download in kb is:-" + filesize / 1024);
            FileOutputStream outputStream = new FileOutputStream(fie);
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            long endTime = System.currentTimeMillis();
            System.out.println("File downloaded");
            System.out.println("Download time in sec. is:-" + (endTime - startTime) / 1000);
            outputStream.close();
            inputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
相关文章