星空网 > 软件开发 > Java

Java8读取文件仅需一行代码

                                                                          Java8读文件仅需一行代码


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

 

  如果你想读入文件作为字符串,那么你还可以使用readAllLines(Path path, Charset cs)方法,此方法与之前的方法相似,也是在读完文件后无需关闭文件。但是它返回的不是字节数组,而是字符串数组。而且,Java8重写了此方法,无需指定字符集,直接使用UTF-8编码进行字符串转换。
如果你想一行一行的读入文件作为字符串,那么你可以使用Files.lines()方法,它会从读入的文件中返回字符串流,并使用UTF-8编码把字节转换成字符。使用forEach()方法,可以只用一行Java代码实现把文件的所有内容输出到控制台,如下面第三个代码片段。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

import java.io.IOException;

import java.nio.charset.StandardCharsets;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.util.List;

  

public class FileReadingTest {

 public static void main(String[] args) throws IOException {

  // Java 7 例子

  // Files.readAllBytes默认以UTF-8编码读入文件,故文件的编码如果不是UTF-8,那么中文内容会出现乱字符

  System.out.println(new String(Files.readAllBytes(Paths.get("D:\\jd.txt"))));

   // Java 8例子

  List<string> <span id="3_nwp" >

<a id="3_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=20&is_

app=0&jk=eca29f2ba2403d7f&k=line&k0=line&kdi0=0&luki=3&mcpm=0&n=10&p=baidu&q=06011078_

cpr&rb=0&rs=1&seller_id=1&sid=7f3d40a22b9fa2ec&ssp2=1&stid=9&t=tpclicked3

_hc&td=1922429&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F6039%2Ehtml&urlid=0" 

target="_blank" mpid="3" >

<span >

line</span></a></span>s = Files.readAllLines(Paths.get("D:\\jd.txt"), StandardCharsets.UTF_8);

  StringBuilder sb = new StringBuilder();

  for(String line : lines){

   sb.append(line);

  }

  String <span id="4_nwp" ><a id="4_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=20&is

_app=0&jk=eca29f2ba2403d7f&k=from&k0=from&kdi0=0&luki=1&mcpm=0&n=10&p=baidu&q=06011078_

cpr&rb=0&rs=1&seller_id=1&sid=7f3d40a22b9fa2ec&ssp2=1&stid=9&t=tpclicked3

_hc&td=1922429&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F6039%2Ehtml&urlid=0"

 target="_blank" mpid="4" ><span >from</span></a></span>File = sb.toString();

        System.out.println(fromFile);

  

 }

}</string>

  如果使用的不是JDK7,而是JDK8,那么一行代码即可完成读文件。

1

2

3

4

5

6

7

8

9

10

11

import static <span id="2_nwp" ><a id="2_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_

id=0&c=news&cf=1001&ch=0&di=128&fv=20&is_app=0&jk=eca29f2ba2403d7f&k=java&k0=java&kdi0=0&luki=5&mcpm=0&n=10&p=baidu&q=06011078_

cpr&rb=0&rs=1&seller_id=1&sid=7f3d40a22b9fa2ec&ssp2=1&stid=9&t=tpclicked3

_hc&td=1922429&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F6039%2Ehtml&urlid=0" target="_blank" mpid="2" 

><span >java</span></a></span>.lang.System.out;

import static java.nio.file.Files.readAllBytes;

import static java.nio.file.Paths.get;

  

import java.io.IOException;

public class FileIntoString {

 public static void main(String[] args) throws IOException {

  // 一行代码搞定读文件,默认是UTF-8编码

  out.println(new String(readAllBytes(get("d:/jd.txt"))));

 }

}

  如果使用JDK8,那么还可以使用流API来读写文件,这样代码更简洁、高效。下面的例子中,lines()方法返回字符串流,字符串使用的是UTF-8编码。如下:

1

2

3

4

5

6

7

8

9

10

11

12

import java.io.IOException;

import java.nio.charset.StandardCharsets;

import java.nio.file.Files;

import java.nio.file.Paths;

  

  

public class Java8FileReader {

 public static void main(String[] args) throws IOException {

  // Java8用流的方式读文件,更加高效

  Files.<span id="1_nwp" ><a id="1_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=20&is_app=0&jk=eca29f2ba2403d7f&k=line&k0=line&kdi0=0&luki=3&mcpm=0&n=10&p=baidu&q=06011078_

cpr&rb=0&rs=1&seller_id=1&sid=7f3d40a22b9fa2ec&ssp2=1&stid=9&t=tpclicked3_

hc&td=1922429&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F6039%2Ehtml&urlid=0" target="_blank" mpid="1" ><span >line</span></a></span>s(Paths.get("D:\\jd.txt"), StandardCharsets.UTF_8).forEach(System.out::println);

 }

}

  上面的例子要注意几点:

  1)文件可能很大,可能会超出内存空间,使用前要做评估。

  2)要输出日志,记录为什么无法读取文件或者在阅读文件时遇到的任何错误。

  3)在把字节转换成字符时,应该指定字符编码。

  4)要处理文件不存在的情况。

  还要注意,如果读入的文件的编码是ANSI编码,那么上面的例子在读取文件内容时会报java.nio.charset.MalformedInputException: Input length = 1错误。

 

 

【最新文档更新请加入尚学堂www.sxt.cn】【专业IT培训机构,真正零首付入学www.bjsxt.com】

 北京尚学堂-cctv央视网广告合作伙伴,专业IT培训机构,口碑最好的java培训、iOS培训、android培训、hadoop大数据培训、web前端培训机构,0元入学,先就业后付款,平均就业薪水9500以上。

 




原标题:Java8读取文件仅需一行代码

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

必应海外广告:https://www.goluckyvip.com/tag/29024.html
必应海外推广:https://www.goluckyvip.com/tag/29025.html
必应竞价推广:https://www.goluckyvip.com/tag/29026.html
必应搜索广告:https://www.goluckyvip.com/tag/29027.html
必应搜索竞价广告:https://www.goluckyvip.com/tag/29028.html
必应搜索推广:https://www.goluckyvip.com/tag/29029.html
武陵山大裂谷周围景点 武陵山大裂谷周围景点图片:https://www.vstour.cn/a/411233.html
南美旅游报价(探索南美洲的旅行费用):https://www.vstour.cn/a/411234.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流