2012-01-19 89 views
5

我使用Jersey來構建RESTful服務,目前我被困在一些我認爲不應該太難的東西上。如何使用Java和Jersey存儲下載的文件?

我設法獲取我想下載的文件,但我不知道如何保存它。

我在網上搜索了答案,但是我沒有找到任何有用的東西來填補我所知道的空白。

請問您能否給我點擊如何繼續以將文件保存在硬盤上的位置?任何代碼示例將被高度讚賞!

   Client client = Client.create(); 

      WebResource imageRetrievalResource = client 
        .resource("http://server/"); 
      WebResource wr=imageRetrievalResource.path("instances/attachment"); 
       MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); 
       queryParams.add("item", "1"); 

       Builder wb=wr.accept("application/json,text/html,application/xhtml+xml,application/xml"); 

       client.addFilter(new HTTPBasicAuthFilter("user","pass")); 

       ClientResponse response= wr.queryParams(queryParams).get(ClientResponse.class); 

       String s= response.getEntity(String.class); 
       System.out.println(response.getStatus()); 

謝謝!

+0

你試過使用'File'類嗎? – Viruzzo

+0

@Viruzo:是的,不管它多麼愚蠢,我沒有設法保存文件實例= – karla

+0

你能發佈你的相關代碼嗎? – Viruzzo

回答

10

我得到的回答我的問題:

 File s= response.getEntity(File.class); 
     File ff = new File("C:\\somewhere\\some.txt"); 
     s.renameTo(ff); 
     FileWriter fr = new FileWriter(s); 
     fr.flush(); 
0

使用高枕無憂客戶這是我做的。

String fileServiceUrl = "http://localhost:8081/RESTfulDemoApplication/files"; 
    RestEasyFileServiceRestfulClient fileServiceClient = ProxyFactory.create(RestEasyFileServiceRestfulClient.class,fileServiceUrl); 

    BaseClientResponse response = (BaseClientResponse)fileServiceClient.getFile("SpringAnnontationsCheatSheet.pdf"); 
    File s = (File)response.getEntity(File.class); 
    File ff = new File("C:\\RestFileUploadTest\\SpringAnnontationsCheatSheet_Downloaded.pdf"); 
    s.renameTo(ff); 
    FileWriter fr = new FileWriter(s); 
    fr.flush(); 
    System.out.println("FileDownload Response = "+ response.getStatus());