File file = new File("C:\testing.txt")
我们能通过任何方式实现吗?比如:
File file = new File("https://stackoverflow.com/ws-server/lookup/1.0/1234")
下面的Web服务以字符串形式向我返回与txt相同的文件内容。https://stackoverflow.com/ws-server/lookup/1.0/1234
有人能告诉我是否可行吗。
您可以将响应写入File
。
请看这个答案了解详细信息。
在此之后,您可以按照习惯打开File
。
这是一个方便的实现吗?注意:它使用Apache HttpComponents客户端和Apache Commons IO
public class RunApp {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://localhost/");
System.out.println("Executing request " + httpget.getRequestLine());
// Create a custom response handler
ResponseHandler<File> responseHandler = new ResponseHandler<File>() {
public File handleResponse( final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
File file = new File("Desired-filename");
IOUtils.copy(entity.getContent(), new FileOutputStream(file));
return file;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
File file = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(file.getAbsolutePath());
} finally {
httpclient.close();
}
}
}
一个更短的解决方案是使用Apache Commons IO 中的FileUtils.copyURLToFile(URL,File(