JDK1.7 之java.nio.file.Files 讀取文件僅需一行代碼實(shí)現(xiàn)
JDK1.7中引入了新的文件操作類java.nio.file這個(gè)包,其中有個(gè)Files類它包含了很多有用的方法來(lái)操作文件,比如檢查文件是否為隱藏文件,或者是檢查文件是否為只讀文件。開(kāi)發(fā)者還可以使用Files.readAllBytes(Path)方法把整個(gè)文件讀入內(nèi)存,此方法返回一個(gè)字節(jié)數(shù)組,還可以把結(jié)果傳遞給String的構(gòu)造器,以便創(chuàng)建字符串輸出。此方法確保了當(dāng)讀入文件的所有字節(jié)內(nèi)容時(shí),無(wú)論是否出現(xiàn)IO異?;蚱渌奈礄z查異常,資源都會(huì)關(guān)閉。這意味著在讀文件到最后的塊內(nèi)容后,無(wú)需關(guān)閉文件。要注意,此方法不適合讀取很大的文件,因?yàn)榭赡艽嬖趦?nèi)存空間不足的問(wèn)題。開(kāi)發(fā)者還應(yīng)該明確規(guī)定文件的字符編碼,以避免任異?;蚪馕鲥e(cuò)誤。
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.
* 注意該方法只適用于簡(jiǎn)單的情況,這種簡(jiǎn)單的情況能夠很方便地將所有的字節(jié)讀進(jìn)一個(gè)字節(jié)數(shù)組,但并不適合用來(lái)讀取大文件
* <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,將拋出內(nèi)存溢出異常
* @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) {
//如果是文本文件也可以這么讀 調(diào)用readAllLines 方法
try {<span style="white-space:pre"> </span>//JDK1.8以后可以省略第二個(gè)參數(shù),默認(rèn)是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 流的方式:
先看源碼實(shí)現(xiàn)
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)方法返回值為L(zhǎng)ist<String>類型,就是為Files.write()而設(shè)計(jì)的
* 因?yàn)镕iles.write()需要傳入一個(gè)Iterable<? extends CharSequence>類型的參數(shù)
*
* Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options)
*/
List<String> stringStream=Files.readAllLines(Paths.get(filePath));
//因?yàn)镕iles.lines(Path path)返回的是Stream<String>,所以可以通過(guò)下面這種方法變成List<String>
//List<String> stringStream2=Arrays.asList((String[])Files.lines(Paths.get(filePath)).toArray());
//StandardOpenOption為枚舉類 ,如果當(dāng)前所Paths.get()的文件不存在,第三個(gè)參數(shù)可選擇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 讀取文件僅需一行代碼實(shí)現(xiàn)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
修改Android應(yīng)用的樣式的一些關(guān)鍵點(diǎn)解析
這篇文章主要介紹了修改Android應(yīng)用的樣式的一些關(guān)鍵點(diǎn),即對(duì)影響外觀的theme跟style的相關(guān)修改,需要的朋友可以參考下2015-12-12
java數(shù)組實(shí)現(xiàn)隊(duì)列及環(huán)形隊(duì)列實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了java數(shù)組實(shí)現(xiàn)隊(duì)列及環(huán)形隊(duì)列實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
Josephus環(huán)的四種解法(約瑟夫環(huán))基于java詳解
這篇文章主要介紹了Josephus環(huán)的四種解法(約瑟夫環(huán))基于java詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
String split方法實(shí)現(xiàn)過(guò)程圖解
這篇文章主要介紹了String split方法實(shí)現(xiàn)過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
HttpClient 請(qǐng)求 URL字符集轉(zhuǎn)碼問(wèn)題
這篇文章主要介紹了HttpClient 請(qǐng)求 URL字符集轉(zhuǎn)碼問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
SpringBoot集成Kaptcha驗(yàn)證碼的詳細(xì)過(guò)程
Kaptcha是一個(gè)強(qiáng)大而靈活的Java驗(yàn)證碼生成庫(kù),通過(guò)合理的配置和使用,它可以有效地提高web應(yīng)用的安全性,防止自動(dòng)化程序的濫用,這篇文章主要介紹了SpringBoot集成Kaptcha驗(yàn)證碼,需要的朋友可以參考下2024-07-07
ResultSet如何動(dòng)態(tài)獲取列名和值
這篇文章主要介紹了ResultSet如何動(dòng)態(tài)獲取列名和值問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
Springboot校驗(yàn)工具類詳細(xì)代碼示例
這篇文章主要給大家介紹了關(guān)于Springboot校驗(yàn)工具類的相關(guān)資料,工具類里面主要是封裝了一些常用字段驗(yàn)證方法,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-02-02

