The world’s Largest Sharp Brain Virtual Experts Marketplace Just a click Away
Levels Tought:
Elementary,Middle School,High School,College,University,PHD
| Teaching Since: | Apr 2017 |
| Last Sign in: | 103 Weeks Ago, 3 Days Ago |
| Questions Answered: | 4870 |
| Tutorials Posted: | 4863 |
MBA IT, Mater in Science and Technology
Devry
Jul-1996 - Jul-2000
Professor
Devry University
Mar-2010 - Oct-2016
Java
 File Input Streams
Create a program that will use FileInputStream to read bytes from a file, display a hex version of the byte and ASCII code -if it’s a printable character
The program should be able to read any file the user selects. Use the JFileChooser dialog. The Swing framework -precursor to JavaFX. Use this code to bring up a dialog box that will allow you to navigate to a file on your computer:
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
System.out.println("File contents: " + file.getAbsolutePath());
System.out.println();
showContents(file);
}
Like mentioned above, use the FileInputStream to read bytes from the selected file.
The code will read 10 bytes at a time, display the hexadecimal representation of the byte, and the ASCII character, if it’s a letter or digit. If it’s not a letter or a digit, then print a period ".".
Put spacing between the hex and the ASCII
Display the 10 bytes in hex first, then the ASCII character
The example for printing, 4 lines of a file:
73 7c 48 6f 67 77 61 72 74 73 s.Hogwarts
7c 45 4e 47 7c 77 61 6e 64 7c .ENG.wand.
7c 31 7c 0d 0a 44 75 6d 62 6c .1...Dumbl
65 64 6f 72 65 7c 41 6c 62 75 edore.Albu
Â
You can get the hex representation of a number in many ways, one way with a wrapper class (Integer.toHexString). You can use this if you want or
 Use the format specifier 'x'. A example: String.format("%02x ", some_byte).Take a byte, and provide a 2 digit hex representation of it. The '0' in the format specifier states that if the hex value is one digit, then left pad it with a '0'. So, a byte value of 15 will be 0F, not F.
Or this method in Character wrapper class.
 Use the isLetterOrDigit() method to determine if the character is printable. This method takes a char as input, the byte has to be type cast to a char.