2025-11-17 16:00:56 +08:00

110 lines
3.5 KiB
Java

package com.cdzy.common.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
public class RemoteFileUtils {
/**
* 获取远程文件并返回File对象
*/
public static File getRemoteFile(String fileUrl) throws IOException {
return getRemoteFile(fileUrl, null);
}
/**
* 获取远程文件并保存到指定路径
*/
public static File getRemoteFile(String fileUrl, String localPath) throws IOException {
validateUrl(fileUrl);
URL url = new URL(fileUrl);
File outputFile;
if (localPath != null && !localPath.trim().isEmpty()) {
outputFile = new File(localPath);
// 确保目录存在
outputFile.getParentFile().mkdirs();
} else {
// 使用临时文件
String extension = getFileExtension(fileUrl);
String prefix = "remote_file_" + System.currentTimeMillis() + "_";
String suffix = extension != null ? "." + extension : ".tmp";
Path tempPath = Files.createTempFile(prefix, suffix);
outputFile = tempPath.toFile();
// 程序退出时删除临时文件
outputFile.deleteOnExit();
}
// 下载文件
try (InputStream in = url.openStream();
FileOutputStream out = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[8192];
int bytesRead;
long totalBytes = 0;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
totalBytes += bytesRead;
}
}
return outputFile;
}
/**
* 获取文件扩展名
*/
private static String getFileExtension(String url) {
if (url == null || url.isEmpty()) {
return null;
}
int lastDotIndex = url.lastIndexOf('.');
int lastSlashIndex = Math.max(url.lastIndexOf('/'), url.lastIndexOf('\\'));
if (lastDotIndex > lastSlashIndex && lastDotIndex < url.length() - 1) {
String extension = url.substring(lastDotIndex + 1);
// 移除可能的查询参数
int paramIndex = extension.indexOf('?');
if (paramIndex != -1) {
extension = extension.substring(0, paramIndex);
}
return extension;
}
return null;
}
/**
* 验证URL格式
*/
private static void validateUrl(String url) {
if (url == null || url.trim().isEmpty()) {
throw new IllegalArgumentException("URL cannot be null or empty");
}
if (!url.startsWith("http://") && !url.startsWith("https://")) {
throw new IllegalArgumentException("URL must start with http:// or https://");
}
}
/**
* 获取文件信息
*/
public static void printFileInfo(File file) {
if (file != null && file.exists()) {
System.out.println("File name: " + file.getName());
System.out.println("File path: " + file.getAbsolutePath());
System.out.println("File size: " + file.length() + " bytes");
System.out.println("Is temporary: " + file.getName().startsWith("remote_file_"));
}
}
}