Java下载windows网络共享文件

以下是使用Java下载Windows网络共享文件的示例代码:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class NetworkFileDownloader {

    public static void main(String[] args) throws MalformedURLException, IOException {
        String fileUrl = "file:computerName/sharedFolder/filename.txt"; // Windows network file path
        String savePath = "C:/downloads/filename.txt"; // Local file path to save the downloaded file

        URL url = new URL(fileUrl);
        URLConnection conn = url.openConnection();
        InputStream inputStream = conn.getInputStream();

        File file = new File(savePath);
        FileOutputStream outputStream = new FileOutputStream(file);

        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.close();
        inputStream.close();

        System.out.println("File downloaded successfully!");
    }

}

在上面的代码中,我们首先定义了Windows网络共享文件的路径和本地文件的保存路径。然后,我们使用Java的URL和URLConnection类来打开网络连接并获取输入流。接下来,我们创建一个本地文件并使用FileOutputStream类将输入流中的字节写入该文件。最后,我们关闭输入输出流并打印成功消息。

请注意,为了访问Windows网络共享文件,我们需要在文件路径中使用 file:// 前缀,并使用计算机名称和共享文件夹名称。此外,我们还需要确保我们有权访问该共享文件夹。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值