_074_NIO_内存映射(3)

========


package 新型IO;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class _003_内存映射
	{

		public static void main(String[] args) throws Exception
			{
			   //内存映射可以直接把文件映射到内存中,而不是通过读操作
				
				RandomAccessFile raf1=new RandomAccessFile("C:\\Users\\Administrator\\Desktop\\test.png", "rw");
				FileChannel fc1=raf1.getChannel();
				
				MappedByteBuffer buffer1=fc1.map(MapMode.READ_WRITE, 0,raf1.length());//最后一个参数是大小,
				       //raf1.length()等于把整个给映射过去了
				int leng=buffer1.capacity();
                 System.out.println("leng"+leng);
                 

 				for(int i=1000;i<=1500;i++) //破坏一些图片的数据
 					{
 						buffer1.put(i,(byte)0);
 					}
 				
 				RandomAccessFile raf2=new RandomAccessFile("C:\\Users\\Administrator\\Desktop\\my.png", "rw");
 				FileChannel fc2=raf2.getChannel();
 				fc2.write(buffer1);
 				
 				fc2.close();
 				fc1.close();
 				raf2.close();
 				raf1.close();
 				
			}

	}

猜你喜欢

转载自blog.csdn.net/yzj17025693/article/details/85650403