你可以使用Java的URL
和URLConnection
类来下载文件到指定文件夹。以下是一个简单的示例代码:
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class DownloadFile {
public static void main(String[] args) {
String fileURL = "http://example.com/file.txt";
String saveDir = "/path/to/save/directory";
try {
URL url = new URL(fileURL);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
File saveDirFile = new File(saveDir);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
String fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
String filePath = saveDir + File.separator + fileName;
FileOutputStream outputStream = new FileOutputStream(filePath);
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded to: " + filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的代码中,你需要将fileURL
替换为要下载的文件的URL,将saveDir
替换为要保存文件的目录路径。然后运行该程序即可将文件下载到指定的文件夹中。