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

 更新时间:2017年11月27日 10:40:06   作者:ljh_learn_from_base  
下面小编就为大家分享一篇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 读取文件仅需一行代码实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Mybatis -如何处理clob类型数据

    Mybatis -如何处理clob类型数据

    这篇文章主要介绍了Mybatis 如何处理clob类型数据的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • java中xml进行报文发送和解析操作

    java中xml进行报文发送和解析操作

    这篇文章主要介绍了java中xml进行报文发送和解析操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-10-10
  • Java 实现文件批量重命名亲测可用(精简版)

    Java 实现文件批量重命名亲测可用(精简版)

    本文给大家分享一段自己写的java代码实现文件批量重命名,亲测试过没有任何问题,大家可以放心使用
    2016-11-11
  • JAVA中堆、栈,静态方法和非静态方法的速度问题

    JAVA中堆、栈,静态方法和非静态方法的速度问题

    这篇文章主要介绍了JAVA中堆、栈,静态方法和非静态方法的速度问题,堆和栈得速度性能分析多角度给大家分析,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2018-08-08
  • Mybatis框架及原理实例分析

    Mybatis框架及原理实例分析

    这篇文章主要介绍了Mybatis框架及原理实例分析,需要的朋友可以参考下
    2017-08-08
  • Java集合类之Map集合的特点及使用详解

    Java集合类之Map集合的特点及使用详解

    这篇文章主要为大家详细介绍一下Java集合类中Map的特点及使用,文中的示例代码讲解详细,对我们学习Java有一定帮助,感兴趣的可以了解一下
    2022-08-08
  • [Spring MVC] -简单表单提交实例

    [Spring MVC] -简单表单提交实例

    本篇文章主要介绍了[Spring MVC] -简单表单提交实例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。
    2016-12-12
  • 如何使用Java 8 中的 Stream 遍历树形结构

    如何使用Java 8 中的 Stream 遍历树形结构

    这篇文章主要介绍了使用Java 8中的Stream遍历树形结构,我们可以使用Java8中的Stream流一次性把数据查出来,然后通过流式处理,我们一起来看看,代码实现为了实现简单,就模拟查看数据库所有数据到List里面,需要的朋友可以参考下
    2023-08-08
  • Java中使用Properties配置文件的简单方法

    Java中使用Properties配置文件的简单方法

    这篇文章主要给大家介绍了关于Java中使用Properties配置文件的简单方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • 基于Springboot吞吐量优化解决方案

    基于Springboot吞吐量优化解决方案

    这篇文章主要介绍了基于Springboot吞吐量优化解决方案,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09

最新评论