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);
//
}
}