Write file with FileChannel
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Util{
public static final int BUFFER_SIZE = 4096;
public void write(File dest, InputStream in) {
FileChannel channel = null;
try {
channel = new FileOutputStream(dest).getChannel();
} catch (FileNotFoundException e) {
System.out.println(e);
}
try {
int byteCount = 0;
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1) {
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, 0, bytesRead);
channel.write(byteBuffer);
byteCount += bytesRead;
}
} catch (IOException e) {
System.out.println(e);
} finally {
try {
if (channel != null) {
channel.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Related examples in the same category