0

I'm having trouble finding what I'm looking for. Is there anyway to read a file by hexadecimal values in java, and to write another file? If I wanted to take one file and create a new file where every hexadecimal value was incremented, how would I do this? Like if I had a txt file that said "Hello" and I increment every hexadecimal value so that it should say "Ifmmp".

How do I read a file (any file, not just an ASCII text file) hexadecimal by hexadecimal, and write another file one hexadecimal at a time?

John T
  • 15
  • 3
  • Why hexadecimal? Increasing a hexidecimal value is the same as increasing a decimal value would it not be? If you wanted to convert from hex to decimal and back you can look at the code on this website: http://www.javamex.com/tutorials/conversion/decimal_hexadecimal.shtml – Riley Carney Dec 08 '15 at 01:39

1 Answers1

0

I believe this is what you're looking for...

Here's code to read from a file and take the hex values of each part in file.

/*
    Code which defines a scanner class and FileInputStream
*/
String lineInFile = scannerName.nextLine();
int[] convertMeToHex = new int[lineInFile.length()];

for (int i = 0; i < convertMeToHex.length; i++)
    convertMeToHex[i] = (int) lineInFile.charAt(i);

String[] hex = new String[convertMeToHex.length];

for (int i = 0; i < convertMeToHex.length; i++)
    hex[i] = Integer.toHexString(convertMeToHex[i]));

You can convert hex back to int with int hexToInt = Integer.parseInt(hexNumber, 16);

Riley Carney
  • 804
  • 5
  • 18
  • So this won't just read a string? I thought nextLine() would just read a string of text. If I use this on something like an image file would it still work the same? – John T Dec 08 '15 at 01:59
  • You would want to work with pictures as well? I assumed by reading a file you meant reading some text or binary file (.dat). When you say read and write to another file, I was assuming a binary or text file (you would have to adjust my above code for a binary file). For other files, you could look up the code, but a way for pictures to turn into a byte array is: http://stackoverflow.com/questions/858980/file-to-byte-in-java – Riley Carney Dec 08 '15 at 02:23
  • http://stackoverflow.com/questions/2817752/java-code-to-convert-byte-to-hexadecimal – Riley Carney Dec 08 '15 at 02:28
  • I literally just mean any file. Load up a microsoft word file and mess with it, open up a jpg image and mess with that, take a music file and mess with that. I mean just a file, regardless of type or intention. The files I'm going to be working with are meant for many different things and don't really fit into any defined type. I'm not really sure what they're for, but messing with them will tell me what they do when they break other things. So, just any and all files. – John T Dec 08 '15 at 02:28