阅读背景:

java 使用 NIO 读写文件

来源:互联网 
!-- flowchart 箭头图标 勿删 --
    public static void Readnio() {
        RandomAccessFile randomAccessFile = null;
        FileChannel fileChannel = null;
        try {
            randomAccessFile = new RandomAccessFile("f:\a.txt", "rw");		//字符文件
           // randomAccessFile = new RandomAccessFile("f:\a.jpg", "rw");	//字节文件
            fileChannel = randomAccessFile.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int read = fileChannel.read(byteBuffer);
            while (read != -1) {
                byteBuffer.flip();	// Buffer切换为读取模式
                while (byteBuffer.hasRemaining()) {
                    System.out.println((char) byteBuffer.get());
					WriteNio(String.valueOf((char) byteBuffer.get()), null);	//写入字符
				//	WriteNio(null, buf);			//写入字节
                }
                byteBuffer.compact();      // 清空Buffer区
                read = fileChannel.read(byteBuffer);     // 继续将数据写入缓存区
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
                if (fileChannel != null) {
                    fileChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    public



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: