[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