Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package test;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import javax.swing.JOptionPane;
- public class BytesExample
- {
- public static byte[] getBytesFromFile(File file) throws IOException {
- InputStream fileInputStream = new FileInputStream(file);
- // Get the size of the file
- long length = file.length();
- // 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 larger than Integer.MAX_VALUE.
- if (length > Integer.MAX_VALUE) {
- }
- // 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=fileInputStream.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());
- }
- // Close the input stream and return bytes
- fileInputStream.close();
- return bytes;
- }
- public static String getHexString(byte[] b) throws Exception
- {
- String result = "";
- for (int i=0; i < b.length; i++)
- {
- result +=
- Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
- }
- return result;
- }
- public static void main(String args[])
- {
- try
- {
- File file = new File("output.txt");
- byte[] arrayOfBytes = getBytesFromFile(file);
- System.out.println(Integer.toBinaryString( (int) arrayOfBytes[1]));
- System.out.println(getHexString(arrayOfBytes));
- }
- catch (IOException e)
- {
- JOptionPane.showMessageDialog(null,
- e.getMessage() +
- "\nError while dealing with files" ,
- "\n... ",
- JOptionPane.PLAIN_MESSAGE);
- }
- catch (Exception e)
- {
- JOptionPane.showMessageDialog(null,
- e.getMessage() +
- "\nKError while converting bytes to String" ,
- "\n... ",
- JOptionPane.PLAIN_MESSAGE);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement