JDK1.7 之java.nio.file.Files 读取文件仅需一行代码实现
JDK1.7中引入了新的文件操作类java.nio.file这个包,其中有个Files类它包含了很多有用的方法来操作文件,比如检查文件是否为隐藏文件,或者是检查文件是否为只读文件。开发者还可以使用Files.readAllBytes(Path)方法把整个文件读入内存,此方法返回一个字节数组,还可以把结果传递给String的构造器,以便创建字符串输出。此方法确保了当读入文件的所有字节内容时,无论是否出现IO异常或其它的未检查异常,资源都会关闭。这意味着在读文件到最后的块内容后,无需关闭文件。要注意,此方法不适合读取很大的文件,因为可能存在内存空间不足的问题。开发者还应该明确规定文件的字符编码,以避免任异常或解析错误。
readAllBytes(Path)方法的源码:
/** *Readsallthebytesfromafile.Themethodensuresthatthefileis *closedwhenallbyteshavebeenreadoranI/Oerror,orotherruntime *exception,isthrown. *注意该方法只适用于简单的情况,这种简单的情况能够很方便地将所有的字节读进一个字节数组,但并不适合用来读取大文件 * Notethatthismethodisintendedforsimplecaseswhereitis *convenienttoreadallbytesintoabytearray.Itisnotintendedfor *readinginlargefiles. * *@parampath *thepathtothefile * *@returnabytearraycontainingthebytesreadfromthefile * *@throwsIOException *ifanI/Oerroroccursreadingfromthestream *如果大于文件2G,将抛出内存溢出异常 *@throwsOutOfMemoryError *ifanarrayoftherequiredsizecannotbeallocated,for *examplethefileislargerthat{@code2GB} *@throwsSecurityException *Inthecaseofthedefaultprovider,andasecuritymanageris *installed,the{@linkSecurityManager#checkRead(String)checkRead} *methodisinvokedtocheckreadaccesstothefile. */
publicstaticbyte[]readAllBytes(Pathpath)throwsIOException{ try(SeekableByteChannelsbc=Files.newByteChannel(path); InputStreamin=Channels.newInputStream(sbc)){//JDK1.7try-with-resource longsize=sbc.size(); if(size>(long)MAX_BUFFER_SIZE) thrownewOutOfMemoryError("Requiredarraysizetoolarge"); returnread(in,(int)size); } }
读取文件只要一行
packageentryNIO; importjava.io.IOException; importjava.nio.file.Files; importjava.nio.file.Paths; publicclassBufferAndChannel{ publicstaticvoidmain(String[]args){ try{ System.out.println( newString(Files.readAllBytes(Paths.get("C:\\FileChannelImpl.java"))) ); }catch(IOExceptione){ e.printStackTrace(); } } }
readAllLines方法的源码
publicstaticListreadAllLines(Pathpath,Charsetcs)throwsIOException{ try(BufferedReaderreader=newBufferedReader(path,cs)){ List result=newArrayList<>(); for(;;){ Stringline=reader.readLine(); if(line==null) break; result.add(line); } returnresult; } }
packageentryNIO; importjava.util.List; importjava.io.IOException; importjava.nio.charset.StandardCharsets; importjava.nio.file.Files; importjava.nio.file.Paths; publicclassBufferAndChannel{ publicstaticvoidmain(String[]args){ //如果是文本文件也可以这么读调用readAllLines方法 try{//JDK1.8以后可以省略第二个参数,默认是UTF-8编码 List lines=Files.readAllLines(Paths.get("C:\\FileChannelImpl.java"),StandardCharsets.UTF_8); StringBuildersb=newStringBuilder(); for(Stringline:lines){ sb.append(line+"\n");//\r\n换行符 } StringfromFile=sb.toString(); System.out.println(fromFile); }catch(IOExceptione){ e.printStackTrace(); } } }
使用Java8流的方式:
先看源码实现
publicstaticStreamlines(Pathpath)throwsIOException{ returnlines(path,StandardCharsets.UTF_8); }
packageentryNIO; importjava.io.IOException; importjava.nio.file.Files; importjava.nio.file.Paths; publicclassBufferAndChannel{ publicstaticvoidmain(String[]args){ //Java8新增lines方法 try{ //Java8用流的方式读文件,更加高效 Files.lines(Paths.get("C:\\FileChannelImpl.java")).forEach(System.out::println); }catch(IOExceptione){ e.printStackTrace(); } } }
读文件一行写文件也只需要一行
packageentryNIO; importjava.util.Arrays; importjava.util.List; importjava.io.IOException; importjava.nio.file.Files; importjava.nio.file.Paths; importjava.nio.file.StandardOpenOption; publicclassBufferAndChannel{ publicstaticvoidmain(String[]args){ //Java8新增lines方法 StringfilePath="C:\\FileChannelImpl.java"; try{ //Java8用流的方式读文件,更加高效 /*Files.lines(Paths.get(filePath)).forEach((line)->{ try{ Files.write(Paths.get("\\1.java"),line.getBytes(),StandardOpenOption.APPEND); //Files.copy(in,target,options); }catch(IOExceptione){ e.printStackTrace(); } });*/ /*Files.readAllLines(Pathpath)方法返回值为List类型,就是为Files.write()而设计的 *因为Files.write()需要传入一个Iterable类型的参数 * *Files.write(Pathpath,Iterablelines,OpenOption...options) */ List stringStream=Files.readAllLines(Paths.get(filePath)); //因为Files.lines(Pathpath)返回的是Stream ,所以可以通过下面这种方法变成List //List stringStream2=Arrays.asList((String[])Files.lines(Paths.get(filePath)).toArray()); //StandardOpenOption为枚举类,如果当前所Paths.get()的文件不存在,第三个参数可选择StandardOpenOption.CREATE_NEW //文件存在则抛java.nio.file.FileAlreadyExistsException异常 Files.write(Paths.get("C:\\2.java"),stringStream,StandardOpenOption.CREATE_NEW); }catch(IOExceptione){ e.printStackTrace(); } } }
以上这篇JDK1.7之java.nio.file.Files读取文件仅需一行代码实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。