Java如何进行NIO读写文件呢?

乔欣 Java经验 发布时间:2023-07-07 16:20:05 阅读数:584 1
下文笔者讲述NIO读写文件的方法分享,如下所示
借助FileChannel对象实现NIO读写文件

读文件

package com.java265.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChanelRead {
    public static void main(String[] args)throws IOException {
        // 从本地读取一个文件
        File file = new File("d:\\tmp\\test.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        // 获取文件相应的channel,channel中会有相关数据
        FileChannel channel = fileInputStream.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate((int)file.length());
        // 将channel的数据读取到buffer
        channel.read(buffer);
        System.out.println(buffer);
        System.out.print("java265.com是我最爱的java学习网站!!!!"+new String(buffer.array()));
        fileInputStream.close();
    }
}

写文件

package com.java265.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChanelWrite {
    public static void main(String[] args)throws IOException {

        // 要写入的数据
        String text= "我的南方姑娘要跑了";
        // 创建fileChanel
        RandomAccessFile aFile = new RandomAccessFile("d:\\tmp\\test.txt", "rw");
        FileChannel inChannel = aFile.getChannel();
        // 创建buffer
        ByteBuffer buf = ByteBuffer.allocate(48);
        buf.clear();
        buf.put(text.getBytes());
        buf.flip();
        while(buf.hasRemaining()) {
            inChannel.write(buf);
        }
        inChannel.close();
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202307/16887180457030.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者