/** * 读文件并且写入另一个文件 */ public static void readAndWrite() throws Exception { //创建一个随机读写文件对象 RandomAccessFile raf=new RandomAccessFile("out.txt","rw"); long totalLen=raf.length(); FileInputStream inputStream = new FileInputStream("out.txt"); FileOutputStream outputStream = new FileOutputStream("out2.txt"); FileChannel inputChannel = inputStream.getChannel(); FileChannel outputChannel = outputStream.getChannel(); MappedByteBuffer allocate /*= ByteBuffer.allocate(2)*/; //size大小决定文件缓冲buffer大小,手动细化操作buffer时需注意,减少OOM allocate=raf.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 100); while (true) { allocate.clear(); // 每次读取完毕后都要 清空 buffer, // 如果不清空buffer inputChannel.read(allocate)永远不会=-1 不会跳出循环,读取到文件的数据也会重复 int read = inputChannel.read(allocate); if (read == -1) { break; } int i=0; for (byte b:"123".getBytes()) { allocate.put(90+i, b); i++; } //实现真实c场景的文件读写,支持断电文件保护,减少OOM allocate.force(); //适配转换数据与文件的格式,减少乱码和写不进去的情况 allocate.flip(); outputChannel.write(allocate); } }
/** * 写文件 * * @throws Exception */ public static void writeFile() throws Exception { FileOutputStream outputStream = new FileOutputStream("out.txt"); FileChannel channel = outputStream.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(50); byteBuffer.put("hello,nio".getBytes()); byteBuffer.flip(); while (byteBuffer.hasRemaining()) { channel.write(byteBuffer); } } /** * 读取文件 * * @throws Exception */ public static void readFile() throws Exception { FileInputStream inputStream = new FileInputStream("out.txt"); FileChannel channel = inputStream.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(20); while (true) { int read = channel.read(byteBuffer); if (-1 == read) { break; } } byteBuffer.flip(); System.out.println(byteBuffer.position() + "," + byteBuffer.limit() + "," + byteBuffer.capacity()); //方法一 //System.out.println(new String(byteBuffer.array())); /*while (byteBuffer.hasRemaining()){ }/ // 方法二 /*while (channel.read(byteBuffer)!=-1){ byte[] array = byteBuffer.array(); System.out.println(new String(array)); byteBuffer.clear(); }*/ //方法三 int i = 0; byte[] bytes = new byte[byteBuffer.capacity()]; while (byteBuffer.hasRemaining()) { bytes[i] = byteBuffer.get(); i++; } System.out.println(new String(bytes)); }
RandomAccessFile优点 1、可以直接跳到文件的任意位置来读写数据 2、允许自由定位文件记录指针,可以不从文件开始的地方进行输出 3、记录指针的方法: long getFilePointer(); 返回文件记录指针的当前位置 void seek(long pos); 将文件记录指针定位到pos位置