Convert byte[] (array) to File using Java

 Posted On  | Yashwant Chavan 

In this tutorial we will learn how to convert byte[] (array) to File using Java.

"hello".getBytes(); encodes given String into a sequence of bytes using the platform's default charset, Which stores the result into a new byte array.

new File("c:\\demo.txt") Creates a new File instance by converting the given pathname string into an abstract pathname.

new FileOutputStream(file) Creates a file output stream to write to the file represented by the specified File object.

os.write(bytes) Writes number of bytes from the specified byte array to output stream.

Convert Byte[] (Array) to File Example

package com.technicalkeeda.app;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;

public class ByteArrayToFileExample {

    public static void main(String[] args) {

        byte[] bytes = "hello".getBytes();
        File file = new File("c:\\demo.txt");

        try {

            OutputStream os = new FileOutputStream(file);
            os.write(bytes);
            System.out.println("Write bytes to file.");
            printContent(file);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void printContent(File file) throws Exception {
        System.out.println("Print File Content");
        BufferedReader br = new BufferedReader(new FileReader(file));

        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        br.close();
    }

}

Output

Write bytes to file.
Print File Content
hello


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0302 seconds.