Convert File To Byte Array Using Java
Posted by tech on
December 10, 2009
|
|
This is a nifty helper method to convert a File object into a byte array. I got this method in Java FAQ.
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 37 38 39 40 41 42 | /** * Returns the contents of the file in a byte array * @param file File this method should read * @return byte[] Returns a byte[] array of the contents of the file */ public static byte[] getBytesFromFile(File file) throws IOException { InputStream is = new FileInputStream(file); System.out.println("\nDEBUG: FileInputStream is " + file); // Get the size of the file long length = file.length(); System.out.println("DEBUG: Length of " + file + " is " + length + "\n"); /* * You cannot create an array using a long type. It needs to be an int * type. Before converting to an int type, check to ensure that file is * not loarger than Integer.MAX_VALUE; */ if (length > Integer.MAX_VALUE) { System.out.println("File is too large to process"); return null; } // Create the byte array to hold the data byte[] bytes = new byte[(int)length]; // Read in the bytes int offset = 0; int numRead = 0; while ((offset < bytes.length) && ((numRead=is.read(bytes, offset, bytes.length-offset)) >= 0)) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } is.close(); return bytes; } |
tags: array, byte, file
No Comments
Java: Convert Stream To Byte[]
Posted by tech on
October 12, 2009
|
|
Say you call an HTTP request that returns a byte array which contains a binary file, how would you do this? First things first. Access it using an HttpURLConnection object. Once you have connected to the URL, get the InputStream object and that is when you will be able to convert the stream into a byte array. Check the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | URL u = new URL("MY URL"); HttpURLConnection uc = (HttpURLConnection) u.openConnection(); String contentType = uc.getContentType(); int contentLength = uc.getContentLength(); if (contentType.startsWith("text/") || contentLength == -1) { throw new IOException("This is not a binary file."); } InputStream raw = uc.getInputStream(); InputStream in = new BufferedInputStream(raw); byte[] data = new byte[contentLength]; int bytesRead = 0; int offset = 0; while (offset < contentLength) { bytesRead = in.read(data, offset, data.length - offset); if (bytesRead == -1) break; offset += bytesRead; } in.close(); |
The data variable is the byte array. You can then do whatever you like (e.g. saving it as a binary file) after you have retrieved the byte array object.
Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.






