import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import org.apache.commons.codec.binary.Base64;
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\admin\\Desktop\\1\\2.png");
byte[] datas = readByNIO(f);
String encodeBase64String = Base64.encodeBase64String(datas);
System.out.println(encodeBase64String);
public static byte[] readByNIO(File file) throws IOException {
FileChannel fileChannel = null;
FileInputStream in = null;
in = new FileInputStream(file);
fileChannel = in.getChannel();
ByteBuffer buffer = ByteBuffer.allocate((int) fileChannel.size());
while (fileChannel.read(buffer) > 0) {
closeChannel(fileChannel);
private static void checkFileExists(File file) throws FileNotFoundException {
if (file == null || !file.exists()) {
System.err.println("file is not null or exist !");
throw new FileNotFoundException(file.getName());
private static void closeChannel(FileChannel channel) {
} catch (IOException e) {
private static void closeOutputStream(OutputStream bos) {
} catch (IOException e) {
private static void closeInputStream(InputStream in) {
} catch (IOException e) {