Skip to content

Instantly share code, notes, and snippets.

@loriopatrick
Created June 2, 2014 19:35
Show Gist options
  • Save loriopatrick/8f8488047ebae22ab9fb to your computer and use it in GitHub Desktop.
Save loriopatrick/8f8488047ebae22ab9fb to your computer and use it in GitHub Desktop.
A simple method to cache web requests.
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
/**
* @author Patrick Lorio
*/
public class WebCache {
public static InputStream GetWeb(String url) throws IOException {
File file = new File("cache/" + URLEncoder.encode(url, "UTF-8"));
if (file.exists()) {
return new FileInputStream(file);
}
OutputStream cacheStream = new FileOutputStream(file);
InputStream webStream = new URL(url).openStream();
return new InputStream() {
@Override
public int read() throws IOException {
int value = webStream.read();
cacheStream.write(value);
return value;
}
@Override
public void close() throws IOException {
super.close();
cacheStream.close();
webStream.close();
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment