一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - JDK1.7 之java.nio.file.Files 讀取文件僅需一行代碼實現

JDK1.7 之java.nio.file.Files 讀取文件僅需一行代碼實現

2021-02-22 10:52ljh_learn_from_base Java教程

下面小編就為大家分享一篇JDK1.7 之java.nio.file.Files 讀取文件僅需一行代碼實現,具有很好的參考價值,希望對大家有所幫助

JDK1.7中引入了新的文件操作類java.nio.file這個包,其中有個Files類它包含了很多有用的方法來操作文件,比如檢查文件是否為隱藏文件,或者是檢查文件是否為只讀文件。開發者還可以使用Files.readAllBytes(Path)方法把整個文件讀入內存,此方法返回一個字節數組,還可以把結果傳遞給String的構造器,以便創建字符串輸出。此方法確保了當讀入文件的所有字節內容時,無論是否出現IO異常或其它的未檢查異常,資源都會關閉。這意味著在讀文件到最后的塊內容后,無需關閉文件。要注意,此方法不適合讀取很大的文件,因為可能存在內存空間不足的問題。開發者還應該明確規定文件的字符編碼,以避免任異常或解析錯誤。

readAllBytes(Path)方法的源碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<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>

讀取文件只要一行

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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方法的源碼

?
1
2
3
4
5
6
7
8
9
10
11
12
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;
    }
  }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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 流的方式:

先看源碼實現

?
1
2
3
public static Stream<String> lines(Path path) throws IOException {
    return lines(path, StandardCharsets.UTF_8);
  }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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();
    }
  }
}

讀文件一行寫文件也只需要一行

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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 讀取文件僅需一行代碼實現就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:http://blog.csdn.net/ljh_learn_from_base/article/details/77760039

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 精品国产品国语在线不卡丶 | 無码一区中文字幕少妇熟女网站 | 美女脱了内裤打开腿让你桶爽 | 久久91精品国产91久久户 | 日韩亚洲欧美一区二区三区 | 欧美日韩亚洲一区二区三区在线观看 | 四虎影院在线免费观看 | 二次元美女脱裤子让男人桶爽 | 日本福利网 | 手机在线免费观看视频 | 亚洲欧美日韩国产精品影院 | 媳妇和公公小说 | 亚洲国产欧美在线人成 | 日韩伦理在线观看 | 国产亚洲人成网站在线观看不卡 | 国产亚洲精品视频中文字幕 | 脱女学小内内摸出水网站免费 | 超强台风免费观看完整版视频 | 欧美乱妇高清无乱码视频在线 | 色综合伊人色综合网站中国 | 奶大逼紧| avav男人天堂 | 久久日韩精品无码一区 | 幻女free性zoz0交 | 国产91区| 精品卡1卡2卡三卡免费视频 | 国产精品区一区二区免费 | chinese特色video | 处女呦呦 | 1313午夜精品理伦片 | 国产亚洲综合精品一区二区三区 | 亚洲国产午夜看片 | 午夜宅男宅女看在线观看 | 国产成人精品999在线 | 激情三级hd中文字幕 | yellow视频在线观看免费 | 国产四虎| 特级淫片欧美高清视频蜜桃 | 亚洲mv国产精品mv日本mv | 99久久国语露脸精品国产 | 超级碰碰青草免费视频92 |