// 通过Java NIO将文本内容写入文本文档中
FileOutputStream outputStream = new FileOutputStream(new File("data.txt"));
FileChannel channel = outputStream.getChannel();
opStream = new ByteSeq(); // 初始化字节型序列
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
String string = "java nio";
byteBuffer.put(string.getBytes());
byteBuffer.flip(); // 调用channel的write方法前必须调用过buffer的flip方法,否则无法正确写入内容
channel.write(byteBuffer);
channel.close();
outputStream.close();
// 查看字节数组的内容
for(int i = 0;i < bytes;i++){
System.out.println(Integer.toHexString(i));
}
// 通过Java NIO、FileChannel实现图片文件的拷贝
FileInputStream inputStream = new FileInputStream("home-hero.jpg"); // 标准的字节流
FileChannel ipStreamChannel = inputStream.getChannel(); // 获取文件通道实例,通过其读写文件
FileOutputStream outputStream = new FileOutputStream("home-hero_new.jpg");
FileChannel opStreamChannel = outputStream.getChannel();
ByteBuffer ipByteBuffer = ByteBuffer.allocateDirect(bufferSize);
int bytes = 0;
Long startTime = System.nanoTime();
while((bytes=ipStreamChannel.read(ipByteBuffer)) != -1){
ipByteBuffer.flip(); // 调用channel的write方法前必须调用过buffer的flip方法,否则无法正确写入内容
opStreamChannel.write(ipByteBuffer);
ipByteBuffer.clear(); // for the next read
/*for(int i = 0;i < bytes;i++){
System.out.println(Integer.toHexString(i));
}*/
}
Long elapsedTime = System.nanoTime() - startTime;
System.out.println("消耗的时间是:" + elapsedTime/1000000000.0 +"秒");
ipStreamChannel.close();
inputStream.close();
opStreamChannel.close();
outputStream.close();
// 通过FileChannel的测试方法
IShijingServiceInterceptor iShijingInterceptor = new IShijingServiceInterceptor();
AuxParams aux = new AuxParams();
ByteSeq bs = new ByteSeq();
FileOutputStream outputStream = new FileOutputStream("E:\\imgtest\\home-hero_new.jpg");
FileChannel opStreamChannel = outputStream.getChannel();
int flag = iShijingInterceptor.getShijingTileByTileId("1111111", bs, aux);
if(flag == 0){
ByteBuffer getByteBuffer = bs.getBuffer();
getByteBuffer.flip(); // 调用channel的write方法前必须调用过buffer的flip方法,否则无法正确写入内容
if(getByteBuffer.hasArray()){
System.out.println("ok.");
}else {
System.out.println("not ok");
}
byte[]bss = getByteBuffer.array();
System.out.println("length:"+bss.length);
opStreamChannel.write(getByteBuffer);
getByteBuffer.clear(); // for the next read
}
opStreamChannel.close();
outputStream.close();
//通过字节数组byte[]的测试方法
IShijingServiceInterceptor iShijingInterceptor = new IShijingServiceInterceptor();
AuxParams aux = new AuxParams();
ByteSeq bs = new ByteSeq();
FileOutputStream outputStream = new FileOutputStream("E:\\imgtest\\home-hero_new.jpg");
int flag = iShijingInterceptor.getShijingTileByTileId("1111111", bs, aux);
if(flag == 0){
ByteBuffer getByteBuffer = bs.getBuffer();
getByteBuffer.flip(); // 调用channel的write方法前必须调用过buffer的flip方法,否则无法正确写入内容
if(getByteBuffer.hasArray()){
System.out.println("ok.");
}else {
System.out.println("not ok");
}
byte[]bss = getByteBuffer.array();
outputStream.write(bss, 0, bss.length);
getByteBuffer.clear(); // for the next read
}
outputStream.close();