java中如何读取文件?
Java  /  管理员 发布于 8年前   161
读取文件有多种方式,基于传统的输入流方式或基于nio的Buffer缓冲对象和管道读取方式甚至非常快速的内存映射读取文件。
java中四种读取文件方式:(推荐:java视频教程)
1、RandomAccessFile:随机读取,比较慢优点就是该类可读可写可操作文件指针
2、FileInputStream:io普通输入流方式,速度效率一般
3、Buffer缓冲读取:基于nio Buffer和FileChannel读取,速度较快
4、内存映射读取:基于MappedByteBuffer,速度最快
RandomAccessFile读取
//RandomAccessFile类的核心在于其既能读又能写public void useRandomAccessFileTest() throws Exception { RandomAccessFile randomAccessFile = new RandomAccessFile(new File("e:/nio/test.txt"), "r"); byte[] bytes = new byte[1024]; int len = 0; while ((len = randomAccessFile.read(bytes)) != -1) { System.out.println(new String(bytes, 0, len, "gbk")); } randomAccessFile.close();}
FielInputStream读取
//使用FileInputStream文件输入流,比较中规中矩的一种方式,传统阻塞IO操作。public void testFielInputStreamTest() throws Exception { FileInputStream inputStream = new FileInputStream(new File("e:/nio/test.txt")); // 使用输入流读取文件,以下代码块几乎就是模板代码 byte[] bytes = new byte[1024]; int len = 0; while ((len = inputStream.read(bytes)) != -1) {// 如果有数据就一直读写,否则就退出循环体,关闭流资源。 System.out.println(new String(bytes, 0, len, "gbk")); } inputStream.close();}
Buffer缓冲对象读取
// nio 读取public void testBufferChannel() throws Exception { FileInputStream inputStream = new FileInputStream(new File("e:/nio/test.txt")); FileChannel fileChannel = inputStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); // 以下代码也几乎是Buffer和Channle的标准读写操作。 while (true) { buffer.clear(); int result = fileChannel.read(buffer); buffer.flip(); if (result == -1) {break; } System.out.println(new String(buffer.array(), 0, result, "gbk")); } inputStream.close();}
内存映射读取
public void testmappedByteBuffer() throws Exception { FileInputStream inputStream = new FileInputStream(new File("e:/nio/test.txt")); FileOutputStream outputStream = new FileOutputStream(new File("e:/nio/testcopy.txt"),true); FileChannel inChannel = inputStream.getChannel(); FileChannel outChannel = outputStream.getChannel(); System.out.println(inChannel.size()); MappedByteBuffer mappedByteBuffer = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size()); System.out.println(mappedByteBuffer.limit()); System.out.println(mappedByteBuffer.position()); mappedByteBuffer.flip(); outChannel.write(mappedByteBuffer); outChannel.close(); inChannel.close(); outputStream.close(); inputStream.close();}//基于内存映射这种方式,这么写好像有问题。MappedByteBuffer和RandomAcessFile这两个类要单独重点研究一下。//TODO 大文件读取
更多java知识请关注java基础教程栏目。
以上就是java中如何读取文件?的详细内容,更多请关注其它相关文章!
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号