Java NIO读写文件

Java NIO读写文件

1.读文件
package com.alibaba.bizworks.ubcp.cportal.promotion.nio;

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

/**
 * @author gf
 * @date 2022/7/1
 */
public class FileChanelRead {
    public static void main(String[] args)throws IOException {
        // 从本地读取一个文件
        File file = new File("d:\\text\\南方姑娘.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("南方姑娘歌词"+new String(buffer.array()));
        fileInputStream.close();

    }
}

运行结果:
Java NIO读写文件_第1张图片

2 写文件
package com.alibaba.bizworks.ubcp.cportal.promotion.nio;

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

/**
 * @author gf
 * @date 2022/7/1
 */
public class FileChanelWrite {
    public static void main(String[] args)throws IOException {

        // 要写入的数据
        String text= "我的南方姑娘要跑了";
        // 创建fileChanel
        RandomAccessFile aFile = new RandomAccessFile("d:\\text\\南方姑娘跑到这里来了.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();
    }
}

运行结果:
Java NIO读写文件_第2张图片
##TODO未完待续

你可能感兴趣的:(Java,java,nio,开发语言)