java nio学习之(二)文件操作

本文展示使用nio操作文件的例子;

package com.example.demo.file;

import org.apache.commons.lang3.StringUtils;

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

public class NioFileUtil {

    public static void main(String[] args) throws Exception {
        System.out.println(read("1.txt"));
        transfer("1.txt","f:\\test\\a.txt");
    }


    public static void write(String message,String destFileName) throws Exception {
        if (StringUtils.isBlank(message)){
            return;
        }
        File file = new File(destFileName);
        FileOutputStream fos = new FileOutputStream(file);
        FileChannel channel = fos.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate((int)file.length());
        buffer.put(message.getBytes());
        // 将buffer的指针指向初始位置
        buffer.flip();
        channel.write(buffer);
        fos.close();

    }


    public static String read(String srcFileName) throws Exception {
        File file = new File(srcFileName);
        FileInputStream inputStream = new FileInputStream(file);
        FileChannel channel = inputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int read = channel.read(byteBuffer);
        inputStream.close();
        return new String(byteBuffer.array(),0,read);
    }

    public static void transfer(String src,String dest) throws Exception{
        FileOutputStream fileOutputStream = new FileOutputStream(dest);
        FileInputStream inputStream = new FileInputStream(src);
        FileChannel destChannel = fileOutputStream.getChannel();
        FileChannel srcChannel = inputStream.getChannel();
        destChannel.transferFrom(srcChannel,0,srcChannel.size());
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值