Searching...
Saturday, 19 October 2013

Java File to Byte Array Example

11:38
package com.pretech;
import java.io.*;
public class FileToByteArray {
	public static void main(String[] args) {
		try {
			File file1 = new File("filetest.txt");
			readFile(file1);
			byte[] myarray = fileToByteArray(file1);
			File file2 = byteArrayToFile(myarray);
			readFile(file2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * Method to convert file to byte array.
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static byte[] fileToByteArray(File file) throws IOException {
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		InputStream inputStream = new FileInputStream(file);
		int nRead;
		byte[] data = new byte[16384];
		while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
			buffer.write(data, 0, nRead);
		}
		buffer.flush();
		return buffer.toByteArray();
	}
	/**
	 * Method to convert byte array to file
	 * 
	 * @param bytearray
	 * @return
	 * @throws IOException
	 */
	public static File byteArrayToFile(byte[] bytearray) throws IOException {
		File file = new File("test.txt");
		file.createNewFile();
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(bytearray);
		fos.close();
		return file;
	}
	/**
	 * Reading a file.
	 * 
	 * @param file
	 * @throws IOException
	 */
	public static void readFile(File file) throws IOException {
		FileReader fr = new FileReader(file);
		BufferedReader br = new BufferedReader(fr);
		String s;
		while ((s = br.readLine()) != null) {
			System.out.println(s);
		}
		fr.close();
	}
}

0 comments: