你可以使用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
替換為要保存文件的目錄路徑。然后運(yùn)行該程序即可將文件下載到指定的文件夾中。