Reads the contents of a file and places it in a byte array. If the name of the file is used as the parameter, as in the above example, the file must be loaded in the sketch's "data" directory/folder. Alternatively, the file maybe be loaded from anywhere on the local computer using an a
(String filename)
| 6550 | * |
| 6551 | */ |
| 6552 | public byte[] loadBytes(String filename) { |
| 6553 | String lower = filename.toLowerCase(); |
| 6554 | // If it's not a .gz file, then we might be able to uncompress it into |
| 6555 | // a fixed-size buffer, which should help speed because we won't have to |
| 6556 | // reallocate and resize the target array each time it gets full. |
| 6557 | if (!lower.endsWith(".gz")) { |
| 6558 | // If this looks like a URL, try to load it that way. Use the fact that |
| 6559 | // URL connections may have a content length header to size the array. |
| 6560 | if (filename.contains(":")) { // at least smells like URL |
| 6561 | InputStream input = null; |
| 6562 | try { |
| 6563 | URL url = new URL(filename); |
| 6564 | URLConnection conn = url.openConnection(); |
| 6565 | int length = -1; |
| 6566 | |
| 6567 | if (conn instanceof HttpURLConnection httpConn) { |
| 6568 | // Will not handle a protocol change (see below) |
| 6569 | httpConn.setInstanceFollowRedirects(true); |
| 6570 | int response = httpConn.getResponseCode(); |
| 6571 | // Default won't follow HTTP -> HTTPS redirects for security reasons |
| 6572 | // http://stackoverflow.com/a/1884427 |
| 6573 | if (response >= 300 && response < 400) { |
| 6574 | String newLocation = httpConn.getHeaderField("Location"); |
| 6575 | return loadBytes(newLocation); |
| 6576 | } |
| 6577 | length = conn.getContentLength(); |
| 6578 | input = conn.getInputStream(); |
| 6579 | } else if (conn instanceof JarURLConnection) { |
| 6580 | length = conn.getContentLength(); |
| 6581 | input = url.openStream(); |
| 6582 | } |
| 6583 | |
| 6584 | if (input != null) { |
| 6585 | byte[] buffer; |
| 6586 | if (length != -1) { |
| 6587 | buffer = new byte[length]; |
| 6588 | int count; |
| 6589 | int offset = 0; |
| 6590 | while ((count = input.read(buffer, offset, length - offset)) > 0) { |
| 6591 | offset += count; |
| 6592 | } |
| 6593 | } else { |
| 6594 | buffer = loadBytes(input); |
| 6595 | } |
| 6596 | input.close(); |
| 6597 | return buffer; |
| 6598 | } |
| 6599 | } catch (MalformedURLException mfue) { |
| 6600 | // not a url, that's fine |
| 6601 | |
| 6602 | } catch (FileNotFoundException fnfe) { |
| 6603 | // Java 1.5+ throws FNFE when URL not available |
| 6604 | // https://download.processing.org/bugzilla/403.html |
| 6605 | |
| 6606 | } catch (IOException e) { |
| 6607 | printStackTrace(e); |
| 6608 | return null; |
| 6609 |
no test coverage detected