[Java Source Code] Convert File to Bytes


/*
 *  Copyright 2009 Eko Kurniawan Khannedy
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package echo.khannedy.sourcecode;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 *
 * @author Eko Kurniawan Khannedy
 */
public class ConvertFileToBytes {

    public static void main(String[] echo) throws FileNotFoundException, IOException {

        // load file
        File file = new File("build.xml");

        // create input stream
        FileInputStream inputStream = new FileInputStream(file);

        // create bytearrayoutputstream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // process read and write data
        byte[] data = new byte[1024];
        int length = 0;
        while ((length = inputStream.read(data)) > 0) {
            outputStream.write(data, 0, length);
        }
        outputStream.flush();

        // result of bytes
        byte[] result = outputStream.toByteArray();

        // close
        inputStream.close();
        outputStream.close();
    }
}

Iklan

Satu pemikiran pada “[Java Source Code] Convert File to Bytes

  1. mas eko,..apa kabar,..mohon maaf ya kalau ada salah !! 😀
    oh iya artikel mas eko bagus semua, termasuk yang ini nanti dirumah mau saya praktek’in cos sekarang lagi di warnet,..hehe
    thanks ya mas

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s