Java 将文件链接转换为 FileInputStream | 代码示例
您可以使用 Java 中的 URL 和 URLConnection 类来打开链接并获取输入流,然后将其转换为 FileInputStream。
以下是将直接下载的文件链接转换为 FileInputStream 的示例代码:
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class DownloadFile {
public static void main(String[] args) {
String fileUrl = 'https://example.com/file.zip';
String savePath = 'C:/downloads/file.zip';
try {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(new File(savePath));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
// Convert FileInputStream
File file = new File(savePath);
FileInputStream fileInputStream = new FileInputStream(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的示例中,我们首先使用 URL 和 URLConnection 打开链接并获取输入流。然后,我们使用 FileOutputStream 将输入流写入本地文件。最后,我们将本地文件转换为 FileInputStream。
原文地址: https://www.cveoy.top/t/topic/oklc 著作权归作者所有。请勿转载和采集!