读取文件有多种方式,基于传统的输入流方式或基于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中如何读取文件?的详细内容。