Reads a file into a byte array. @param query The query being handled (for logging purposes). @param file The file to read. @param max_length The maximum number of bytes to read from the file. @return null if the file doesn't exist or is empty or couldn't be read, otherwise a byte array of up
(final HttpQuery query,
final File file,
final int max_length)
| 594 | * read, otherwise a byte array of up to {@code max_length} bytes. |
| 595 | */ |
| 596 | private static byte[] readFile(final HttpQuery query, |
| 597 | final File file, |
| 598 | final int max_length) { |
| 599 | final int length = (int) file.length(); |
| 600 | if (length <= 0) { |
| 601 | return null; |
| 602 | } |
| 603 | FileInputStream in; |
| 604 | try { |
| 605 | in = new FileInputStream(file.getPath()); |
| 606 | } catch (FileNotFoundException e) { |
| 607 | return null; |
| 608 | } |
| 609 | try { |
| 610 | final byte[] buf = new byte[Math.min(length, max_length)]; |
| 611 | final int read = in.read(buf); |
| 612 | if (read != buf.length) { |
| 613 | logError(query, "When reading " + file + ": read only " |
| 614 | + read + " bytes instead of " + buf.length); |
| 615 | return null; |
| 616 | } |
| 617 | return buf; |
| 618 | } catch (IOException e) { |
| 619 | logError(query, "Error while reading " + file, e); |
| 620 | return null; |
| 621 | } finally { |
| 622 | try { |
| 623 | in.close(); |
| 624 | } catch (IOException e) { |
| 625 | logError(query, "Error while closing " + file, e); |
| 626 | } |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | /** |
| 631 | * Attempts to read the cached {@code .json} file for this query. |
no test coverage detected