nio读取文件并分行

package nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;

public class NIOFile {
    public static void main(String[] args) throws Exception {
        FileInputStream inputStream = new FileInputStream("E://mysvn/java/Thread/src/main/java/nio/to.csv");
//        FileInputStream inputStream = new FileInputStream("E://laptofxindekeyanptc.rar");

        FileChannel inChannel = inputStream.getChannel();
        //分配1KB
        //文件格式为UTF-8
        char en = '\n';
        ByteBuffer buffer = ByteBuffer.allocate(200000);
        int readedbyte = inChannel.read(buffer);
        byte[] by = buffer.array();
        ByteBuffer lineBuffer = ByteBuffer.allocate(10000);
        for (int i = 0; i < readedbyte; i++) {
            lineBuffer.put(by[i]);
            if (by[i] == en) {
                int position = lineBuffer.position();
                byte[] lineArray = lineBuffer.array();
                String lineStr = new String(lineArray, 0, position, "utf-8");
                System.out.println(lineStr);
                lineBuffer.clear();
            }
        }
        System.out.println(readedbyte);
    }
}

 

package noSelect;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author:li
 * @Date:created in 2018/1/17 17:13
 */
public class FileChannelDemo {
    public static void main(String[] args) throws Exception {
        FileInputStream inputStream = new FileInputStream("F://binary.zip");

        FileChannel inChannel = inputStream.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024 * 1000);
        long size = 0;
        int readedbyte = inChannel.read(buffer);
        while (readedbyte != -1) {
            size = size + readedbyte;
            buffer.clear();
            readedbyte = inChannel.read(buffer);
            System.out.println(readedbyte);
        }
        inChannel.close();
        inChannel.close();
        System.out.println(size);
        System.out.println(638512763);
        System.out.println(623548 / 1024.0);
        System.out.println(size / 1024 / 1024.0);
//
    }
}

 

转载于:https://my.oschina.net/marjeylee/blog/1602762

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值