JDK1.7 之java.nio.file.Files 读取文件仅需一行代码实现
时间:2019-04-10
本文章向大家介绍JDK1.7 之java.nio.file.Files 读取文件仅需一行代码实现,主要包括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 读取文件仅需一行代码实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
- ASM 翻译系列第三十三弹:REQUIRED_MIRROR_FREE_MB的含义
- 放弃Python转向Go语言:这9大理由就够了 !(附代码)
- CCKiller:Linux轻量级CC攻击防御工具,秒级检查、自动拉黑和释放
- 利用HSTS安全协议柔性解决全站HTTPS的兼容性问题
- Nginx内容替换模块http_substitutions_filter_module及实用案例分享
- libmemcached编译安装报错解决记录
- 解决网站静态缓存后WP-PostViews插件不计数的问题
- Haproxy安装部署文档及多配置文件管理方案
- ASM 翻译系列第三十四弹:ASM磁盘组重要属性介绍
- 博客集成Hitokoto·一言经典语句功能
- 博客网页导致电脑CPU飙升的问题解决记录
- 恢复WordPress分类目录的别名链接形式
- 替代crontab,统一定时任务管理系统cronsun简介
- 小网站最简单实用的动静分离优化方案
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- 基于thinkphp6.0的success、error实现方法
- Yii框架模拟组件调用注入示例
- 解决laravel 表单提交-POST 异常的问题
- laravel5.0在linux下解决.htaccess无效和去除index.php的问题
- laravel返回统一格式错误码问题
- 使用 PHP Masked Package 屏蔽敏感数据的实现方法
- PHP简单实现图片格式转换(jpg转png,gif转png等)
- 在thinkphp5.0路径中实现去除index.php的方式
- Laravel5.5 手动分页和自定义分页样式的简单实现
- laravel自定义分页的实现案例offset()和limit()
- Laravel6.0.4中将添加计划任务事件的方法步骤
- Laravel 不同生产环境服务器的判断实践
- 解决thinkPHP 5 nginx 部署时,只跳转首页的问题
- Laravel 类和接口注入相关的代码
- laravel unique验证、确认密码confirmed验证以及密码修改验证的方法