Mega Code Archive

 
Categories / Java / File Input Output
 

Read file with FileChannel

import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class Util {   public static final int BUFFER_SIZE = 4096;   public void read(File src, OutputStream dest) {     FileChannel channel = null;     int bytesRead = -1;     try {       channel = new FileInputStream(src).getChannel();       ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);       while ((bytesRead = channel.read(buffer)) != -1) {         buffer.flip();         dest.write(buffer.array(), 0, bytesRead);         buffer.clear();       }     } catch (Exception e) {       System.out.println(e);     } finally {       try {         if (dest != null) {           dest.flush();           dest.close();         }         if (channel != null) {           channel.close();         }       } catch (IOException e) {         e.printStackTrace();       }     }   } }