java 使用 NIO 读写文件

    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 static void WriteNio(String str, ByteBuffer byteBuffer) {
        RandomAccessFile randomAccessFile = null;
        FileChannel fileChannel = null;
        try {
            randomAccessFile = new RandomAccessFile("f:\\b.txt", "rw");		//字符文件
         //  randomAccessFile = new RandomAccessFile("f:\\b.jpg", "rw");	//字节文件
            randomAccessFile.seek(randomAccessFile.length());           //防止覆盖原文件内容
            fileChannel = randomAccessFile.getChannel();
            ByteBuffer byteBuffer1 = ByteBuffer.wrap(str.getBytes());
            fileChannel.write(byteBuffer1);	 //写入字符            
         //   fileChannel.write(byteBuffer);	//写入字节

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

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

    }

猜你喜欢

转载自blog.csdn.net/eaphyy/article/details/83896823