Java tutorial
//package com.java2s; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { /** * Writes the given byte array as a local file. * * @param array the byte array to read from * @param outputFileName the name of the file to write to * @return the URL for the local file */ public static String writeFile(byte[] array, String outputFileName) throws IOException { InputStream in = new ByteArrayInputStream(array); try { return writeStreamToFile(in, outputFileName); } finally { in.close(); } } /** * Writes the contents from the given input stream to the given file. * * @param in the InputStream to read from * @param outputFileName the name of the file to write to * @return the URL for the local file */ public static String writeStreamToFile(InputStream in, String outputFileName) throws IOException { File file = new File(outputFileName); // Create the parent directory. file.getParentFile().mkdirs(); OutputStream out = new FileOutputStream(file); try { copy(in, out); // Return the URL to the output file. return file.toURI().toString(); } finally { out.flush(); out.close(); } } private static void copy(InputStream in, OutputStream out) throws IOException { out = new BufferedOutputStream(out, 0x1000); in = new BufferedInputStream(in, 0x1000); // Copy the contents from the input stream to the output stream. while (true) { int b = in.read(); if (b == -1) { break; } out.write(b); } out.flush(); } }