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

ต่อไปนี้เป็นตัวอย่างของ Java.io.FileOutputStream ที่ใช้ในการแปลง bytes array ไปเป็นไฟล์. โดยจะทำการอ่านข้อมูลจาก "C:\\users\\nopphanan7\\file.txt" แล้วทำการแปลงเป็น bytes array จากนั้นก็เขียนออกมาใส่ในไฟล์ "C:\\users\\nopphanan7\\file2.txt" ครับ.
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
34
35
36
package demo.file;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
 
public class ArrayOfBytesToFileExample {
 
    /**
     * @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();
 
            // convert array of bytes into file
            FileOutputStream fileOuputStream = new FileOutputStream(
                    "C:\\users\\nopphanan7\\file2.txt");
            fileOuputStream.write(bFile);
            fileOuputStream.close();
 
            System.out.println("\n" + "Convert array of bytes to file is done");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
ผลลัพธ์ที่ได้คือ
1
Convert array of bytes to file 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