欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JDK1.7 之java.nio.file.Files 读取文件仅需一行代码实现

程序员文章站 2023-12-14 13:43:22
jdk1.7中引入了新的文件操作类java.nio.file这个包,其中有个files类它包含了很多有用的方法来操作文件,比如检查文件是否为隐藏文件,或者是检查文件是否为只...

jdk1.7中引入了新的文件操作类java.nio.file这个包,其中有个files类它包含了很多有用的方法来操作文件,比如检查文件是否为隐藏文件,或者是检查文件是否为只读文件。开发者还可以使用files.readallbytes(path)方法把整个文件读入内存,此方法返回一个字节数组,还可以把结果传递给string的构造器,以便创建字符串输出。此方法确保了当读入文件的所有字节内容时,无论是否出现io异常或其它的未检查异常,资源都会关闭。这意味着在读文件到最后的块内容后,无需关闭文件。要注意,此方法不适合读取很大的文件,因为可能存在内存空间不足的问题。开发者还应该明确规定文件的字符编码,以避免任异常或解析错误。

readallbytes(path)方法的源码:

<span style="font-size:32px;"> </span><span style="font-size:18px;">/** 
 * reads all the bytes from a file. the method ensures that the file is 
 * closed when all bytes have been read or an i/o error, or other runtime 
 * exception, is thrown. 
 * 注意该方法只适用于简单的情况,这种简单的情况能够很方便地将所有的字节读进一个字节数组,但并不适合用来读取大文件 
 * <p> note that this method is intended for simple cases where it is 
 * convenient to read all bytes into a byte array. it is not intended for 
 * reading in large files. 
 * 
 * @param  path 
 *     the path to the file 
 * 
 * @return a byte array containing the bytes read from the file 
 * 
 * @throws ioexception 
 *     if an i/o error occurs reading from the stream 
 *     如果大于文件2g,将抛出内存溢出异常 
 * @throws outofmemoryerror 
 *     if an array of the required size cannot be allocated, for 
 *     example the file is larger that {@code 2gb} 
 * @throws securityexception 
 *     in the case of the default provider, and a security manager is 
 *     installed, the {@link securitymanager#checkread(string) checkread} 
 *     method is invoked to check read access to the file. 
 */</span><span style="font-size:18px;"> 
  public static byte[] readallbytes(path path) throws ioexception { 
    try (seekablebytechannel sbc = files.newbytechannel(path); 
       inputstream in = channels.newinputstream(sbc)) {//jdk1.7 try-with-resource 
      long size = sbc.size(); 
      if (size > (long)max_buffer_size) 
        throw new outofmemoryerror("required array size too large"); 
 
      return read(in, (int)size); 
    } 
  }</span> 

读取文件只要一行

package entrynio; 
 
import java.io.ioexception; 
import java.nio.file.files; 
import java.nio.file.paths; 
 
public class bufferandchannel { 
  public static void main(string[] args) { 
    try { 
        system.out.println( 
         new string(files.readallbytes(paths.get("c:\\filechannelimpl.java"))) 
        ); 
       
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } 
  } 
} 

readalllines方法的源码

public static list<string> readalllines(path path, charset cs) throws ioexception { 
    try (bufferedreader reader = newbufferedreader(path, cs)) { 
      list<string> result = new arraylist<>(); 
      for (;;) { 
        string line = reader.readline(); 
        if (line == null) 
          break; 
        result.add(line); 
      } 
      return result; 
    } 
  } 
package entrynio; 
 
import java.util.list; 
import java.io.ioexception; 
import java.nio.charset.standardcharsets; 
import java.nio.file.files; 
import java.nio.file.paths; 
 
public class bufferandchannel { 
  public static void main(string[] args) { 
    //如果是文本文件也可以这么读 调用readalllines 方法 
    try {<span style="white-space:pre">               </span>//jdk1.8以后可以省略第二个参数,默认是utf-8编码 
      list<string> lines = files.readalllines(paths.get("c:\\filechannelimpl.java"), standardcharsets.utf_8); 
      stringbuilder sb = new stringbuilder(); 
      for (string line : lines) { 
        sb.append(line+"\n");// \r\n 换行符 
      } 
      string fromfile = sb.tostring(); 
      system.out.println(fromfile); 
 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } 
  } 
} 

使用java8 流的方式:

先看源码实现

public static stream<string> lines(path path) throws ioexception { 
    return lines(path, standardcharsets.utf_8); 
  } 
package entrynio; 
 
import java.io.ioexception; 
import java.nio.file.files; 
import java.nio.file.paths; 
 
public class bufferandchannel { 
  public static void main(string[] args) { 
    //java8 新增lines方法 
    try { 
       // java8用流的方式读文件,更加高效  
      files.lines(paths.get(<span style="font-family: arial, helvetica, sans-serif;">"c:\\filechannelimpl.java"</span>)).foreach(system.out::println);  
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } 
  } 
} 

读文件一行写文件也只需要一行

package entrynio; 
 
import java.util.arrays; 
import java.util.list; 
import java.io.ioexception; 
import java.nio.file.files; 
import java.nio.file.paths; 
import java.nio.file.standardopenoption; 
public class bufferandchannel { 
  public static void main(string[] args){ 
    //java8 新增lines方法 
    string filepath="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 (ioexception e) { 
            e.printstacktrace(); 
          } 
         
      }); */ 
       
      /* files.readalllines(path path)方法返回值为list<string>类型,就是为files.write()而设计的 
       * 因为files.write()需要传入一个iterable<? extends charsequence>类型的参数 
       * 
       * files.write(path path, iterable<? extends charsequence> lines, openoption... options) 
       */ 
      list<string> stringstream=files.readalllines(paths.get(filepath)); 
      //因为files.lines(path path)返回的是stream<string>,所以可以通过下面这种方法变成list<string> 
      //list<string> 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 (ioexception e) { 
      e.printstacktrace(); 
    } 
  } 
} 

以上这篇jdk1.7 之java.nio.file.files 读取文件仅需一行代码实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:

下一篇: