/** * This method attempts to copy the complete content of passed input stream into a file at path * "to". using copy options as passed in by user. For acceptable copy options see {@link * Files#copy(InputStream, Path, CopyOption...)} method. The passed in stream will be attempted to * be completely consumed. In any outcome (success or exception), the stream will be closed. */ public static void copy(final InputStream from, final Path to, final CopyOption... options) throws IOException { checkNotNull(from); checkNotNull(to); DirSupport.mkdir(to.getParent()); try (final InputStream is = from) { Files.copy(is, to, options); } catch (IOException e) { Files.delete(to); } }
/** * Writes out the content of a string payload into a file using given charset. The file will be * overwritten if exists and parent directories will be created if needed. */ public static void writeFile(final Path file, final Charset charset, final String payload) throws IOException { checkNotNull(file); checkNotNull(charset); checkNotNull(payload); DirSupport.mkdir(file.getParent()); try (final BufferedWriter writer = Files.newBufferedWriter(file, charset)) { writer.write(payload); writer.flush(); } }