在 Java 中將位元組寫入檔案

Rupam Yadav 2023年10月12日
  1. 在 Java 中使用 FileOutputStream 將位元組寫入檔案
  2. 使用 java.nio.file 將位元組寫入檔案
  3. 在 Java 中使用 Apache Commons IO 庫將位元組寫入檔案
在 Java 中將位元組寫入檔案

該程式演示瞭如何在 Java 中將位元組陣列寫入檔案。可以使用 FileOutputStream 和本文中提到的一些庫來執行此任務。

在 Java 中使用 FileOutputStream 將位元組寫入檔案

Java 中的類 FileOutputStream 是用於將資料或位元組流寫入檔案的輸出流。建構函式 FileOutputStream(File file) 建立一個檔案輸出流以寫入由 File 物件 file 表示的檔案,我們在下面的程式碼中建立了該檔案。

String 型別的變數 s 被傳遞給 getBytes() 方法,該方法將字串轉換為位元組序列並返回位元組陣列。write() 方法將位元組陣列作為引數,並將位元組陣列 b 中的 b.length 個位元組寫入此檔案輸出流。

在給定的路徑上建立了一個副檔名為 .txt 的檔案,如果我們開啟它,我們可以看到與儲存在變數 s 中的字串相同的內容。

import java.io.File;
import java.io.FileOutputStream;

public class ByteToFile {
  public static void main(String args[]) {
    File file = new File("/Users/john/Desktop/demo.txt");
    try {
      FileOutputStream fout = new FileOutputStream(file);
      String s = "Example of Java program to write Bytes using ByteStream.";
      byte b[] = s.getBytes();
      fout.write(b);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

使用 java.nio.file 將位元組寫入檔案

Java NIO ( New I/O) 包由適用於檔案、目錄的靜態方法組成,並且主要適用於 Path 物件。Path.get() 是一種將字串序列或路徑字串轉換為路徑的靜態方法。它只是呼叫 FileSystems.getDefault().getPath()

因此,我們可以使用 Files.write() 方法將位元組陣列 b 寫入檔案,方法是將路徑傳遞給檔案,並將位元組陣列轉換為字串。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ByteToFile {
  public static void main(String args[]) {
    Path p = Paths.get("/Users/john/Desktop/demo.txt");
    try {
      String s = "Write byte array to file using java.nio";
      byte b[] = s.getBytes();
      Files.write(p, b);
    } catch (IOException ex) {
      System.err.format("I/O Error when copying file");
    }
  }
}

在 Java 中使用 Apache Commons IO 庫將位元組寫入檔案

這個庫的 maven 依賴如下。

   <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
   </dependency>

Apache Commons IO 庫有 FilesUtils 類,它有 writeByteArrayToFile() 方法。此方法採用目標路徑和我們正在寫入的二進位制資料。如果我們的目標目錄或檔案不存在,它們將被建立。如果檔案存在,則在寫入前將其截斷。

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;

public class ByteToFile {
  public static void main(String args[]) {
    {
      File file = new File("doc.txt");
      byte[] data =
          "Here, we describe the general principles of 																									 photosynthesis"
              .getBytes(StandardCharsets.UTF_8);
      try {
        FileUtils.writeByteArrayToFile(file, data);
        System.out.println("Successfully written data to the file");
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

輸出:

Successfully written data to the file
作者: Rupam Yadav
Rupam Yadav avatar Rupam Yadav avatar

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

LinkedIn

相關文章 - Java Byte

相關文章 - Java File