1 22 package org.objectweb.petals.util; 23 24 import java.io.File ; 25 import java.io.FileOutputStream ; 26 import java.io.IOException ; 27 import java.io.InputStream ; 28 import java.nio.ByteBuffer ; 29 import java.nio.channels.Channels ; 30 import java.nio.channels.FileChannel ; 31 import java.nio.channels.ReadableByteChannel ; 32 33 38 public final class NioUtil { 39 40 43 private static final int BUFFER_SIZE = 4096; 44 45 48 private NioUtil() { 49 super(); 50 } 51 52 60 public static void copyStreamToFile(InputStream is, File aFile) 61 throws IOException { 62 63 ReadableByteChannel inputChannel = Channels.newChannel(is); 64 65 FileOutputStream fos = new FileOutputStream (aFile); 66 FileChannel outputChannel = fos.getChannel(); 67 68 ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); 69 70 int readBytes; 71 while ((readBytes = inputChannel.read(buffer)) != -1) { 72 if (readBytes > 0) { 73 buffer.flip(); 74 outputChannel.write(buffer); 75 76 buffer.clear(); 77 } 78 } 79 80 try { 81 inputChannel.close(); 82 outputChannel.close(); 83 fos.close(); 84 } catch (IOException ioe) { 85 } 87 88 } 89 90 } 91 | Popular Tags |