如何在 Java 中將檔案的內容寫入位元組陣列?


FileInputStream 類包含一個 read() 方法,此方法接受一個位元組陣列作為引數,並將檔案輸入流的資料讀入給定的位元組陣列中。

示例

import java.io.File;
import java.io.FileInputStream;

public class FileToByteArray {
   public static void main(String args[]) throws Exception {
      File file = new File("HelloWorld");
      FileInputStream fis = new FileInputStream(file);
      byte[] bytesArray = new byte[(int)file.length()];
      fis.read(bytesArray);
      String s = new String(bytesArray);
      System.out.println(s);
   }
}

輸出

//Class declaration
public class SampleProgram {
   /* This is my first java program.
      This will print 'Hello World' as the output
   */

   //Main method
   public static void main(String []args) {
      //prints Hello World
      System.out.println("Hello World");
   }
}

更新於: 19-Dec-2019

808 次瀏覽

開啟你的事業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.