如何將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");
   }
}

更新於: 2019-12-19

808 瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.