Reputation: 86687
Reading a HTTP remote file and save it to the local disk is as easy as:
org.apache.commons.io.FileUtils.copyURLToFile(new URL("http://path/to.file"), new File("localfile.txt"));
But I'd like to read a file without having to save it to the disk, just keep it in memory and read from there.
Is that possible?
Upvotes: 1
Views: 1399
Reputation: 3508
Nice to see that you're using apache commons, you can do the following: -
final URL url = new URL("http://pat/to.tile");
final String content = IOUtils.toString(url.openStream(), "UTF-8"); // or your preferred encoding
Alternatively, you can just access the stream and do as you want with it. You don't need to use apache commons to get a String
if you use an InputStreamReader
, but there's no reason not to since you're already using commons-io
As others have mentioned, if you just want it in memory without processing the stream into String, just url.openStream()
Upvotes: 2
Reputation: 29119
If you are happy to introduce 3rd party libraries then OkHttp has an example that does this.
OkHttpClient client = new OkHttpClient();
String url = "http://pat/to.tile";
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
String urlContent = response.body().string();
The library would also parse and make available all HTTP protocol related headers etc.
Upvotes: 0
Reputation: 910
You can do this like:
public static String getContent(String url) throws Exception {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
}
Upvotes: 0
Reputation: 2731
You can use java.net.URL#openStream()
InputStream input = new URL("http://pat/to.tile").openStream();
// ...
Upvotes: 4