25 janeiro 2018

FileInputStream / FileOutputStream - new ways to code

From Java7 that we must use FileInputStream and FileOuputStream as described below

public void writeToFile(String fileName, byte[] content) throws IOException {
    try (OutputStream os = Files.newOutputStream(Paths.get(fileName))) {
        os.write(content);
    }
}
public byte[] readFromFile(String fileName) throws IOException {
    byte[] buf = new byte[8192];
    try (InputStream is = Files.newInputStream(Paths.get(fileName))) {
        int len = is.read(buf);
        if (len < buf.length) {
            return Arrays.copyOf(buf, len);
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream(16384);
        while (len != -1) {
            os.write(buf, 0, len);
            len = is.read(buf);
        }
        return os.toByteArray();
    }
}

Source: dzone.com

Sem comentários: