共計 928 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中,可以使用 URLConnection
類來下載文件到本地。以下是一個簡單的示例代碼:
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {public static void main(String[] args) {String fileUrl = "http://example.com/sample.jpg";
String saveDir = "C:/Downloads/";
try {URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
FileOutputStream outputStream = new FileOutputStream(saveDir + fileName);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded successfully!");
} catch (IOException e) {e.printStackTrace();
}
}
}
在上面的代碼中,我們首先指定了要下載的文件的 URL 和保存目錄,然后創建一個 URL 對象并打開連接。接下來,我們獲取輸入流并創建一個輸出流,將下載的文件寫入到本地。最后關閉輸入流和輸出流,下載完成。
請注意,上述示例中的 URL 和保存目錄是示例值,您需要根據實際情況修改為您要下載的文件的 URL 和保存目錄。
丸趣 TV 網 – 提供最優質的資源集合!
正文完