package com.mesopotamia.test;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Scanner; import org.apache.log4j.Logger;
/*
* 原文学习请加微信订阅号:it_pupil
* **/
public class FileRead {
private static Logger logger = Logger.getLogger(FileRead.class);
public static void main(String args[]) throws FileNotFoundException{
String path = "C:" + File.separator + "test" + File.separator + "Alice.txt";
readFile3(path);
} public static void readFile(String path) throws FileNotFoundException {
long start = System.currentTimeMillis();//开始时间
int bufSize = 1024;//1K缓冲区
File fin = new File(path);
/*
* 通道就是为操作文件而建立的一个连接。(读写文件、内存映射等)
* 此处的getChannel()可以获取通道;
* 用FileChannel.open(filename)也可以创建一个通道。
* "r"表示只读。
*
* RandomAccessFile是独立与I/O流家族的类,其父类是Object。
* 该类因为有个指针可以挪动,所以,可以从任意位置开始读取文件数据。
* **/
FileChannel fcin = new RandomAccessFile(fin, "r").getChannel();
//给字节缓冲区分配大小
ByteBuffer rBuffer = ByteBuffer.allocate(bufSize);
String enterStr = "\n";
try {
byte[] bs = new byte[bufSize];
String tempString = null;
while (fcin.read(rBuffer) != -1) {//每次读1k到缓冲区
int rSize = rBuffer.position();//记录缓冲区当前位置
rBuffer.rewind();//位置归零,标记取消,方便下次循环重新读入缓冲区。
rBuffer.get(bs);//将缓冲区数据读到字节数组中
rBuffer.clear();//清除缓冲
/*
* 用默认编码将指定字节数组的数据构造成一个字符串
* bs:指定的字节数组,0:数组起始位置;rSize:数组结束位置
* */
tempString = new String(bs, 0, rSize);
int fromIndex = 0;//每次读的开始位置
int endIndex = 0;//每次读的结束位置
//按行读String数据
while ((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1) {
String line = tempString.substring(fromIndex, endIndex);//转换一行
System.out.print(line);
fromIndex = endIndex + 1;
}
}
long end = System.currentTimeMillis();//结束时间
System.out.println("传统IO读取数据,指定缓冲区大小,总共耗时:"+(end - start)+"ms"); } catch (IOException e) {
e.printStackTrace();
}
} public static void readFile1(String path) {
long start = System.currentTimeMillis();//开始时间
File file = new File(path);
if (file.isFile()) {
/*使用Reader家族,表示我要读字符数据了,
*使用该家族中的BufferedReader,表示我要建立缓冲区读字符数据了。
* */
BufferedReader bufferedReader = null;
FileReader fileReader = null;
try {
fileReader = new FileReader(file);
//嵌套使用,装饰者模式,老生常谈。装饰者模式的使用,可以读前面小砖写的《从熏肉大饼到装饰者模式》
bufferedReader = new BufferedReader(fileReader);
String line = bufferedReader.readLine();
//一行一行读
while (line != null) { //按行读数据
System.out.println(line);
line = bufferedReader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//最后一定要关闭
try {
fileReader.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();//结束时间
System.out.println("传统IO读取数据,不指定缓冲区大小,总共耗时:"+(end - start)+"ms");
} }
} public static void readFile3(String path) {
long start = System.currentTimeMillis();//开始时间
long fileLength = 0;
final int BUFFER_SIZE = 0x300000;// 3M的缓冲
File file = new File(path);
fileLength = file.length();
try {
/*使用FileChannel.map方法直接把整个fileLength大小的文件映射到内存中**/
MappedByteBuffer inputBuffer = new RandomAccessFile(file, "r").getChannel()
.map(FileChannel.MapMode.READ_ONLY, 0, fileLength);// 读取大文件
byte[] dst = new byte[BUFFER_SIZE];// 每次读出3M的内容
//每3M做一个循环,分段将inputBuffer的数据取出。
for (int offset = 0; offset < fileLength; offset += BUFFER_SIZE) {
//防止最后一段不够3M
if (fileLength - offset >= BUFFER_SIZE) {
//一个字节一个字节的取出来放到byte[]数组中。
for (int i = 0; i < BUFFER_SIZE; i++)
dst[i] = inputBuffer.get(offset + i);
} else {
for (int i = 0; i < fileLength - offset; i++)
dst[i] = inputBuffer.get(offset + i);
}
// 将得到的3M内容给Scanner,这里的XXX是指Scanner解析的分隔符。
Scanner scan = new Scanner(new ByteArrayInputStream(dst)).useDelimiter("XXX");
//hasNext()所参照的token就是上面的XXX
while (scan.hasNext()) {
// 这里为对读取文本解析的方法
System.out.print(scan.next() + "XXX");
}
scan.close();
}
System.out.println();
long end = System.currentTimeMillis();//结束时间
System.out.println("NIO 内存映射读大文件,总共耗时:"+(end - start)+"ms");
} catch (Exception e) {
e.printStackTrace();
}
}
}

  

Java读取文件的几种方式的更多相关文章

  1. java读取文件的几种方式性能比较

    //普通输入流读取文件内容 public static long checksumInputStream(Path filename) { try(InputStream in= Files.newI ...

  2. 【文件下载】Java下载文件的几种方式

    [文件下载]Java下载文件的几种方式  摘自:https://www.cnblogs.com/sunny3096/p/8204291.html 1.以流的方式下载. public HttpServl ...

  3. 精通awk系列(3):铺垫知识:读取文件的几种方式

    回到: Linux系列文章 Shell系列文章 Awk系列文章 读取文件的几种方式 读取文件有如下几种常见的方式: 下面使用Shell的read命令来演示前4种读取文件的方式(第五种按字节数读取的方式 ...

  4. Java读写文件的几种方式

    自工作以后好久没有整理Java的基础知识了.趁有时间,整理一下Java文件操作的几种方式.无论哪种编程语言,文件读写操作时避免不了的一件事情,Java也不例外.Java读写文件一般是通过字节.字符和行 ...

  5. java复制文件的4种方式

    尽管Java提供了一个可以处理文件的IO操作类.但是没有一个复制文件的方法.复制文件是一个重要的操作,当你的程序必须处理很多文件相关的时候.然而有几种方法可以进行Java文件复制操作,下面列举出4中最 ...

  6. [JAVA]java复制文件的4种方式

    尽管Java提供了一个可以处理文件的IO操作类. 但是没有一个复制文件的方法. 复制文件是一个重要的操作,当你的程序必须处理很多文件相关的时候. 然而有几种方法可以进行Java文件复制操作,下面列举出 ...

  7. java 下载文件的两种方式和java文件的上传

    一:以网络的方式下载文件 try { // path是指欲下载的文件的路径. File file = new File(path); // 以流的形式下载文件. InputStream fis = n ...

  8. java 读取文件内容 三种形式及效率对比

    IOUtils.getStringFromReader() 读取方式为最快的 InputStream in = null; String line = ""; long start ...

  9. java追加文件的几种方式

    import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.FileWriter; import ja ...

随机推荐

  1. 2.struts2访问web资源(在struts2中获取session,request等等)

    什么是web资源:web资源就是指request,response,session,servlet的api 为什么需要访问web资源:因为图片上传,需要获取图片的目录,就需要通过action来访问we ...

  2. <一>Angular.js学习

    angular.module(name, [a], [b]);  // angular.module()创建.获取.注册angular中的模块 name:字符串类型,代表模块的名称: a:字符串的数组 ...

  3. (转)maven配置之pom.xml配置

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  4. WCF在tcp通道下启用httpget

    关于tcp通道下,启用httpget,必须启用一个http的基地址,如果要启用元数据交换,host中必须开启服务描述. //01 create host Uri tcpBaseAddress = ne ...

  5. oracle字符查出一位

    select cast('a' as varchar2(64)) from dual;

  6. Volley简单封装

    public interface IRequest { /** * 获取头部信息 * * @return */ public Map<String, String> getHeaderMa ...

  7. Guava学习笔记:Google Guava 类库简介

    http://www.cnblogs.com/peida/tag/Guava/ Guava 是一个 Google 的基于java1.6的类库集合的扩展项目,包括 collections, cachin ...

  8. sql server 按分组拼接数据

    SELECT B.id , LEFT(tempname, LEN(tempname) - 1) AS name FROM ( SELECT id , ( SELECT name + ',' FROM ...

  9. Myeclipse 安装离线adt的方法 ()

    方法一: 1.下载最新的adt插件ADT-10.0.1.zip (在MyEclipse 10.5 上安装的ADT插件是ADT 20.0.3离线包下载地址: http://dl.cr173.com//s ...

  10. zTree树的模糊搜索

    工作需要,所以做了一个比较方便的搜索功能:1.功能实现都是基于zTree的API:2.如有更好的建议,欢迎拍我:其中要说明下的是flag 这个字段, 这是我自己定义的扩展字段,代码中涉及到flag 请 ...