IO NIO(new io)
面向流 面向缓冲
阻塞IO 非阻塞IO
无 选择器
public static void main1(String[] args){
long start = System.currentTimeMillis();
FileInputStream in = null;
FileOutputStream fout = null;
ByteArrayOutputStream out = null;
int size = -1;
try {
in = new FileInputStream(new File("C:/t0183085951624797df.jpg")); //文件读取地址
fout = new FileOutputStream(new File("C:/new.jpg"));//文件写入地址
out = new ByteArrayOutputStream();
byte[] img =new byte[1024];
while((size=in.read(img))!=-1){
out.write(img, 0, size); //base64转码
fout.write(img, 0, size); //保存到本地
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
BASE64Encoder encoder = new BASE64Encoder();
long end = System.currentTimeMillis();
System.out.println("用时为:" + (end-start));
System.out.println("base64转码:"+ encoder.encode(out.toByteArray()));
}
public static void main2(String[] args) {
long start = System.currentTimeMillis();
FileInputStream in = null;
FileOutputStream fout = null;
byte[] img = null;
try {
in = new FileInputStream(new File("C:/t0183085951624797df.jpg")); //文件读取地址
fout = new FileOutputStream(new File("C:/new2.jpg"));//文件写入地址
img = new byte[in.available()];//in.available()数据流字节数(如果网路间断会出现读取不完整)
in.read(img);//写入字节数组中
fout.write(img);//写入文件中
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
long end = System.currentTimeMillis();
System.out.println("用时为:" + (end-start));
System.out.println("base64转码:"+ encoder.encode(img));
}
public static void main3(String[] args) {
long start = System.currentTimeMillis();
FileInputStream fin = null;
ByteArrayOutputStream out = null;
FileOutputStream fout = null;
try {
fin = new FileInputStream(new File("C:/t0183085951624797df.jpg")); //文件读取地址
fout = new FileOutputStream(new File("C:/new3.jpg"));//文件写入地址
out = new ByteArrayOutputStream();
FileChannel channel = fin.getChannel(); //获取通道
int allocate = 1024;// 字节
ByteBuffer bf = ByteBuffer.allocate(allocate); //创建缓存区
int length = -1;
while ((length = channel.read(bf)) != -1) { //将通道中的数据写入缓冲区,并判断通道中的数据是否到末尾
/*
* 注意,读取后,将位置置为0,将limit置为容量, 以备下次读入到字节缓冲中,从0开始存储
*/
byte[] bytes = bf.array(); //将缓存数据转成byte数据组
out.write(bytes, 0, length); //将byte数组写入到:ByteArrayOutputStream
fout.write(bytes, 0, length); //将byte数组写入文件中
bf.clear();
}
channel.close();
// 加密
BASE64Encoder encoder = new BASE64Encoder();
long end = System.currentTimeMillis();
System.out.println("用时为:" + (end-start));
System.out.println("base64转码:"+ encoder.encode(out.toByteArray()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}