如何在异步httpclient java 11中将多个异步get请求的响应写入单个文件?

如何在异步httpclient java 11中将多个异步get请求的响应写入单个文件?,java,httpclient,java-11,asynchttpclient,sendasync,Java,Httpclient,Java 11,Asynchttpclient,Sendasync,我可以使用Java11中的httpclient下载一个媒体文件,如下所示 public class Httptest { private static HttpClient client = HttpClient.newBuilder().build(); public static void main(String[] args) throws Exception { File fts = new File("P:/

我可以使用Java11中的httpclient下载一个媒体文件,如下所示

public class Httptest {
    
    private static HttpClient client = HttpClient.newBuilder().build();
            
    public static void main(String[] args) throws Exception {
        File fts = new File("P:/sample.ts");  //Destination of downloaded file
        fts.createNewFile();
        URI url = new URI("File url here"); //File Url
        
        HttpRequest request = HttpRequest.newBuilder()   //Creating HttpRequest using Builder class
                .GET()
                .uri(url)
                .build();
        Path file = Path.of("P:/samp.ts");
        //BodyHandlers class has methods to handle the response body
        // In this case, save it as a file (BodyHandlers.ofFile())
        HttpResponse<Path> response = client.send(request,BodyHandlers.ofFile(file)); 
    }
}

在执行结束时创建的文件
sample.ts
没有请求响应。
如果您了解我的问题的要点,有人能为这个问题提出替代解决方案吗。

一种可能是与将字节写入文件的
使用者一起使用。这将允许您控制文件的打开方式,允许您附加到现有文件,而不是每次创建新文件


请注意,如果这样做,则不应使用
sendAsync
,因为请求将同时发送,因此响应也将同时接收。如果仍要同时发送请求,则需要缓冲响应,并在将响应写入文件时进行一些同步。

是。谢谢你的回答,我在异步和并发方面犯了一些小错误<代码>消费者
修复了此问题。
public class httptest{
    
   // Concurrent requests are made in 4 threads
   private static ExecutorService executorService = Executors.newFixedThreadPool(4); 

   //HttpClient built along with executorservice
   private static HttpClient client = HttpClient.newBuilder() 
            .executor(executorService)
            .build();
    
   public static void main(String[] args) throws Exception{
        File fts = new File("P:/Spyder_directory/sample.ts");
        fts.createNewFile();
        List<URI> urls = Arrays.asList(
                         new URI("Url of file 1"),
                         new URI("Url of file 2"),
                         new URI("Url of file 3"),
                         new URI("Url of file 4"),
                         new URI("Url of file 5"));
        
        
        List<HttpRequest> requests = urls.stream()
                .map(HttpRequest::newBuilder)
                .map(requestBuilder -> requestBuilder.build())
                .collect(toList());
        Path file = Path.of("P:/Spyder_directory/sample.ts");
        List<CompletableFuture<HttpResponse<Path>>> results = requests.stream()
                .map(individual_req -> client.sendAsync(individual_req,BodyHandlers.ofFile(file)))
                .collect(Collectors.toList());
   }
}