1. 程式人生 > 程式設計 >java中建立、寫入檔案的5種方式

java中建立、寫入檔案的5種方式

在java中有很多的方法可以建立檔案寫檔案,你是否真的認真的總結過?下面筆者就幫大家總結一下java中建立檔案的五種方法。

  1. Files.newBufferedWriter(Java 8)
  2. Files.write(Java 7 推薦)
  3. PrintWriter
  4. File.createNewFile
  5. FileOutputStream.write(byte[] b) 管道流

實際上不只這5種,通過管道流的排列組合,其實有更多種,但是筆者總結的這五種可以說是最常用及最佳實踐,

前提小知識

以前我在寫技術文章涉及到“流關閉”、“連線關閉”的時候,經常有人留言:“還寫技術文章,寫個流都不知道close()”,這種留言我遇到過無數回!

在本文中大量的使用到了try-with-resources語法,這個語法真的是很久的了,但是的確還有小夥伴不知道(知道的小夥伴就略過吧)。我還是說一下,下文中的管道流不是我沒close,是自動關閉close的。

try(管道流、連線等實現了Closeable介面的類){
  //這裡使用類物件操作
}
//用try()包含起來,就不用在finally裡面自己手動的去 Object.close()了,會自動的關閉

1. Java 8 Files.newBufferedWriter

java8 提供的newBufferedWriter可以建立檔案,並向檔案內寫入資料。可以通過追加寫模式,向檔案內追加內容。

@Test
void testCreateFile1() throws IOException {
  String fileName = "D:\\data\\test\\newFile.txt";

  Path path = Paths.get(fileName);
  // 使用newBufferedWriter建立檔案並寫檔案
  // 這裡使用了try-with-resources方法來關閉流,不用手動關閉
  try (BufferedWriter writer =
          Files.newBufferedWriter(path,StandardCharsets.UTF_8)) {
   writer.write("Hello World -建立檔案!!");
  }

  //追加寫模式
  try (BufferedWriter writer =
        Files.newBufferedWriter(path,StandardCharsets.UTF_8,StandardOpenOption.APPEND)){
    writer.write("Hello World -字母哥!!");
  }
}

2. Java 7 Files.write

下面的這種方式Files.write,是筆者推薦的方式,語法簡單,而且底層是使用Java NIO實現的。同樣提供追加寫模式向已經存在的檔案種追加資料。這種方式是實現文字檔案簡單讀寫最方便快捷的方式。

@Test
void testCreateFile2() throws IOException {
  String fileName = "D:\\data\\test\\newFile2.txt";

  // 從JDK1.7開始提供的方法
  // 使用Files.write建立一個檔案並寫入
  Files.write(Paths.get(fileName),"Hello World -建立檔案!!".getBytes(StandardCharsets.UTF_8));

  // 追加寫模式
  Files.write(
     Paths.get(fileName),"Hello World -字母哥!!".getBytes(StandardCharsets.UTF_8),StandardOpenOption.APPEND);
}

3. PrintWriter

PrintWriter是一個比較古老的檔案建立及寫入方式,從JDK1.5就已經存在了,比較有特點的是:PrintWriter的println方法,可以實現一行一行的寫檔案。

@Test
void testCreateFile3() throws IOException {
  String fileName = "D:\\data\\test\\newFile3.txt";

  // JSD 1.5開始就已經存在的方法
  try (PrintWriter writer = new PrintWriter(fileName,"UTF-8")) {
   writer.println("Hello World -建立檔案!!");
   writer.println("Hello World -字母哥!!");
  }

  // Java 10進行了改進,支援使用StandardCharsets指定字符集
  /*try (PrintWriter writer = new PrintWriter(fileName,StandardCharsets.UTF_8)) {

   writer.println("first line!");
   writer.println("second line!");

  } */

}

4. File.createNewFile()

createNewFile()方法的功能相對就比較純粹,只是建立檔案不做檔案寫入操作。 返回true表示檔案成功,返回 false表示檔案已經存在.可以配合FileWriter 來完成檔案的寫操作。

@Test
void testCreateFile4() throws IOException {
  String fileName = "D:\\data\\test\\newFile4.txt";

  File file = new File(fileName);

  // 返回true表示檔案成功
  // false 表示檔案已經存在
  if (file.createNewFile()) {
   System.out.println("建立檔案成功!");
  } else {
   System.out.println("檔案已經存在不需要重複建立");
  }

  // 使用FileWriter寫檔案
  try (FileWriter writer = new FileWriter(file)) {
   writer.write("Hello World -建立檔案!!");
  }

}

5.最原始的管道流方法

最原始的方式就是使用管道流巢狀的方法,但是筆者覺得這種方法歷久彌新,使用起來非常靈活。你想去加上Buffer緩衝,你就巢狀一個BufferedWriter,你想去向檔案中寫java物件你就巢狀一個ObjectOutputStream。但歸根結底要用到FileOutputStream。

@Test
void testCreateFile5() throws IOException {
  String fileName = "D:\\data\\test\\newFile5.txt";
  try(FileOutputStream fos = new FileOutputStream(fileName);
   OutputStreamWriter osw = new OutputStreamWriter(fos);
   BufferedWriter bw = new BufferedWriter(osw);){
   bw.write("Hello World -建立檔案!!");
   bw.flush();
  }
}

以上就是java中建立、寫入檔案的5種方式的詳細內容,更多關於Java 建立、寫入檔案的資料請關注我們其它相關文章!