Channel
import java.nio.channels.Channel;
public interface Channel extends Closeable {
public boolean isOpen();
public void close() throws IOException;
}
public static void exampleForChannel() throws IOException {
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
Channel channel;
FileChannel fileChannel = null;
fileChannel.read(byteBuffer);
fileChannel.write(byteBuffer);
ServerSocketChannel serverSocketChannel;
SocketChannel socketChannel;
DatagramChannel datagramChannel;
}
public static void exampleForChannel_3() throws IOException {
String filePath = "D:\\temp\\c\\0325\\1616577053009.txt";
FileInputStream fileInputStream = new FileInputStream(filePath);
FileChannel fileChannel = fileInputStream.getChannel();
String filePath2 = "D:\\temp\\c\\0325\\"+System.currentTimeMillis()+".txt";
File file = new File(filePath2);
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(filePath2);
FileChannel fileChannel2 = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(5);
while(true) {
byteBuffer.clear();
int read = fileChannel.read(byteBuffer);
if(read == -1) {
break;
}
byteBuffer.flip();
fileChannel2.write(byteBuffer);
}
fileInputStream.close();
fileOutputStream.close();
System.out.println("文件拷贝完毕=======");
}
public static void exampleForChannel_4() throws IOException {
String filePath = "D:\\temp\\c\\0325\\12.jpg";
FileInputStream fileInputStream = new FileInputStream(filePath);
FileChannel source = fileInputStream.getChannel();
String filePath2 = "D:\\temp\\c\\0325\\"+System.currentTimeMillis()+".jpg";
File file = new File(filePath2);
FileOutputStream fileOutputStream = new FileOutputStream(file);
FileChannel destion = fileOutputStream.getChannel();
destion.transferFrom(source, 0, source.size());
source.close();
destion.close();
fileInputStream.close();
fileOutputStream.close();
System.out.println("文件拷贝完毕=======");
}
Buffer
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
public static void exampleForBuffer() {
IntBuffer intBuffer = IntBuffer.allocate(5);
for(int i = 0;i<intBuffer.capacity();i++) {
intBuffer.put(2*i);
}
intBuffer.flip();
intBuffer.position(1);
intBuffer.limit(3);
while(intBuffer.hasRemaining()) {
System.out.println(intBuffer.get());
}
}
public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>{
final int[] hb;
}
public abstract class Buffer {
private int mark = -1;
private int position = 0;
private int limit;
private int capacity;
}