( begin auto-generated from loadBytes.xml ) Reads the contents of a file or url and places it in a byte array. If a file is specified, it must be located in the sketch's "data" directory/folder. The filename parameter can also be a URL to a file found online. For security reasons, a Pr
(String filename)
| 7331 | * |
| 7332 | */ |
| 7333 | public byte[] loadBytes(String filename) { |
| 7334 | String lower = filename.toLowerCase(); |
| 7335 | // If it's not a .gz file, then we might be able to uncompress it into |
| 7336 | // a fixed-size buffer, which should help speed because we won't have to |
| 7337 | // reallocate and resize the target array each time it gets full. |
| 7338 | if (!lower.endsWith(".gz")) { |
| 7339 | // If this looks like a URL, try to load it that way. Use the fact that |
| 7340 | // URL connections may have a content length header to size the array. |
| 7341 | if (filename.contains(":")) { // at least smells like URL |
| 7342 | InputStream input = null; |
| 7343 | try { |
| 7344 | URL url = new URL(filename); |
| 7345 | URLConnection conn = url.openConnection(); |
| 7346 | int length = -1; |
| 7347 | |
| 7348 | if (conn instanceof HttpURLConnection) { |
| 7349 | HttpURLConnection httpConn = (HttpURLConnection) conn; |
| 7350 | // Will not handle a protocol change (see below) |
| 7351 | httpConn.setInstanceFollowRedirects(true); |
| 7352 | int response = httpConn.getResponseCode(); |
| 7353 | // Default won't follow HTTP -> HTTPS redirects for security reasons |
| 7354 | // http://stackoverflow.com/a/1884427 |
| 7355 | if (response >= 300 && response < 400) { |
| 7356 | String newLocation = httpConn.getHeaderField("Location"); |
| 7357 | return loadBytes(newLocation); |
| 7358 | } |
| 7359 | length = conn.getContentLength(); |
| 7360 | input = conn.getInputStream(); |
| 7361 | } else if (conn instanceof JarURLConnection) { |
| 7362 | length = conn.getContentLength(); |
| 7363 | input = url.openStream(); |
| 7364 | } |
| 7365 | |
| 7366 | if (input != null) { |
| 7367 | byte[] buffer = null; |
| 7368 | if (length != -1) { |
| 7369 | buffer = new byte[length]; |
| 7370 | int count; |
| 7371 | int offset = 0; |
| 7372 | while ((count = input.read(buffer, offset, length - offset)) > 0) { |
| 7373 | offset += count; |
| 7374 | } |
| 7375 | } else { |
| 7376 | buffer = loadBytes(input); |
| 7377 | } |
| 7378 | input.close(); |
| 7379 | return buffer; |
| 7380 | } |
| 7381 | } catch (MalformedURLException mfue) { |
| 7382 | // not a url, that's fine |
| 7383 | |
| 7384 | } catch (FileNotFoundException fnfe) { |
| 7385 | // Java 1.5+ throws FNFE when URL not available |
| 7386 | // http://dev.processing.org/bugs/show_bug.cgi?id=403 |
| 7387 | |
| 7388 | } catch (IOException e) { |
| 7389 | printStackTrace(e); |
| 7390 | return null; |
no test coverage detected