การแปลงไฟล์เป็น Bytes Arrays ใน Java

ตัว Java.io.FileInputStream นั้นเราสามารถเแปลง File object เป็น bytes array ได้ครับ
ตัวอย่าง เช่น
ในตัวอย่างเราจะทำการอ่านข้อมูลจากไฟล์ "C:\\users\\nopphanan7\\file.txt" แล้วแปลงเป็น bytes array และแสดงเนื้อหาในไฟล์ออกมาออกทางหน้าจอครับ
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
package demo.file;
 
import java.io.File;
import java.io.FileInputStream;
 
public class FileToArrayOfBytesExample {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
 
        File file = new File("C:\\users\\nopphanan7\\file.txt");
 
        byte[] bFile = new byte[(int) file.length()];
 
        try {
            // convert file into array of bytes
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bFile);
            fileInputStream.close();
 
            for (int i = 0; i < bFile.length; i++) {
                System.out.print((char) bFile[i]);
            }
 
            System.out.println("Convert File To Array Of Bytes Is Done");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
ผลลัพธ์ที่ได้คือ
1
2
Test File To Array Of Bytes Example
Convert File To Array Of Bytes Is Done.

About Nop

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment