以下是使用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:// 前缀,并使用计算机名称和共享文件夹名称。此外,我们还需要确保我们有权访问该共享文件夹。