Java8讀取檔案僅需一行代碼-北京尚學堂,java8一行

來源:互聯網
上載者:User

Java8讀取檔案僅需一行代碼-北京尚學堂,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" style="width: auto; height: auto; float: none;">

<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" style="text-decoration: none;">

<span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">

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" style="width: auto; height: auto; float: none;"><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" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">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" style="width: auto; height: auto; float: none;"><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" 

style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">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" style="width: auto; height: auto; float: none;"><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" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">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以上。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.