java远程下载文件

java远程下载文件

/**
 * 创建一个临时文件
 * @param url 远端文件Url
 * @return File
 */
private static File getFile(String url) {
    //对本地文件命名
    String fileName = "temp";
    File file = null;
    URL urlfile;
    try {
        // 创建一个临时路径
        file = File.createTempFile("file", fileName);
        //下载
        urlfile = new URL(url);
        InputStream inStream = urlfile.openStream();
        OutputStream os =  new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        inStream.close();
    } catch (Exception e) {
    }
    return file;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java中的Apache Commons Net库来实现远程FTP下载文件的功能。以下是一个简单的示例代码: ```java import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import java.io.FileOutputStream; import java.io.IOException; public class FTPDownloadExample { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String user = "username"; String password = "password"; String remoteFilePath = "/path/to/remote/file.txt"; String localFilePath = "C:/path/to/local/file.txt"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(user, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); FileOutputStream outputStream = new FileOutputStream(localFilePath); boolean success = ftpClient.retrieveFile(remoteFilePath, outputStream); outputStream.close(); if (success) { System.out.println("文件成功下载到本地路径: " + localFilePath); } else { System.out.println("文件下载失败"); } ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的示例中,你需要将`server`、`port`、`user`和`password`替换为你的FTP服务器的相关信息。`remoteFilePath`是远程服务器上要下载文件的路径,`localFilePath`是要保存到本地的文件路径。 该示例使用FTPClient类的`retrieveFile()`方法来下载文件,并使用FileOutputStream类将文件保存到本地路径。成功下载后,将在控制台上显示成功消息,否则将显示失败消息。 请注意,为了运行此示例,你需要将Apache Commons Net库添加到你的Java项目中。你可以从Apache的官方网站下载并导入所需的JAR文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值