import java.nio.*;
import java.util.Scanner;
public class F1 {
public static void main(String[] args) {
ByteBuffer bu = ByteBuffer.allocate(20);
bu.put(new Scanner(System.in).nextLine().trim().getBytes());
bu.flip();
System.out.println(bu.get());
bu.flip();
//这里要注意输出之后,flip反转之后长度只有一了
System.out.println("1----" + bu.limit());
byte[] byt = new byte[bu.limit()];
bu.get(byt);// 只获取单个字节
System.out.println(new String(byt));
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class F2 {
public static void main(String[] args) throws Exception {
FileInputStream fin = new FileInputStream("D:\\zuoye/o.txt");
FileOutputStream fout = new FileOutputStream("D:\\zuoye/q1.txt");
FileChannel finc = fin.getChannel();//输入流转换成通道
FileChannel foutc =fout.getChannel();//输入流转换成通道
ByteBuffer bf = ByteBuffer.allocate(fin.available());
finc.read(bf);//对于ByteBuffer来讲,现在是写的模式,写进内存里
System.out.println(new String(bf.array()));
bf.flip();//还原所有的文件指针
foutc.write(bf);//对于ByteBuffer来讲,现在是读的模式 从内存中读出来
bf.clear();
fin.close();
fout.close();
}
}
大文件的复制
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
public class F3 {
public static void main(String[] args) throws Exception {
FileChannel big=new RandomAccessFile("D:\\zuoye/o.txt","rw").getChannel();
//fileChannel不能单独被打开
//,需要通过使用一个InputStream、
//OutputStream或RandomAccessFile来获取一个FileChannel实例
FileChannel cha=new RandomAccessFile("D:\\zuoye/q2.txt","rw").getChannel();
//会在内存中映射一个和原文件大小的内存块
MappedByteBuffer map=big.map(MapMode.READ_WRITE, 0, big.size());
big.read(map);
map.flip();
cha.write(map);
map.clear();
big.close();
cha.close();
/*这里有个问题,如果q2.txt里有文字,且比o的长度长,o
* 里的内容不会写到q2里*/
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class F4 {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("D:\\zuoye/o.txt");
FileOutputStream out = new FileOutputStream("D:\\zuoye/q3.txt");
FileChannel inf = in.getChannel();
FileChannel outf = out.getChannel();
ByteBuffer by = ByteBuffer.allocate(1024);
int i;
while ((i = inf.read(by)) != -1) {
by.flip();
outf.write(by);
by.clear();
}
inf.close();
outf.close();
in.close();
out.close();
}
}