⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 filechanneltest.java

📁 精通java核心技术》随书源代码
💻 JAVA
字号:
// ==================== Program Discription =====================// 程序名称:示例2-2 : FileChannelTest.java// 程序目的:学习java nio#FileChannel// ==============================================================import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.io.File;import java.io.RandomAccessFile;import java.io.IOException;public class FileChannelTest{	public static void main (String [] argv)		throws IOException	{		//创建一个临时的文件		File temp = File.createTempFile ("temp", null);		RandomAccessFile file = new RandomAccessFile (temp, "rw");		FileChannel channel = file.getChannel();		// 创建一个Buffer		ByteBuffer byteBuffer = ByteBuffer.allocateDirect (100);		insertData (0, byteBuffer, channel);		insertData (60, byteBuffer, channel);		insertData (600, byteBuffer, channel);		System.out.println ("Wrote temp file '" + temp.getPath()+ "', size=" + channel.size());		System.out.println(channel.position());		file.seek(100);		System.out.println("after file.seek(100),position="+channel.position());					getData(0,byteBuffer,channel);		channel.close();		file.close();	}		private static void getData(int position,ByteBuffer buffer,FileChannel channel)throws IOException	{		String temp="";		buffer.clear();		channel.position(position);		channel.read(buffer,60);	    buffer.flip();		System.out.println(buffer.asCharBuffer().toString().getBytes ("US-ASCII"));		//System.out.println(buffer);	}			private static void insertData (int position, ByteBuffer buffer,		FileChannel channel)		throws IOException	{		String string = "#<- position" + position;		buffer.clear();		buffer.put (string.getBytes ("US-ASCII"));		buffer.flip();		channel.position (position);		channel.write (buffer);	}}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -