-4

how do I read any file like images , videos , text Files .... etc

as an hex String then write these String again in other place but with ability to open file as original

I'm looking for a code ??

Thanks in advance

BlackRoot
  • 504
  • 1
  • 9
  • 29
  • Is it a filecopy program you are asking? – BDRSuite Dec 01 '14 at 14:18
  • 6
    you don't read as hex string. You always read bytes, but then you may convert the byte stream to a hex-string for whatever purpose. – cello Dec 01 '14 at 14:18
  • @vembutech no it doesn't a copy program it's for another purpose – BlackRoot Dec 01 '14 at 14:22
  • @cello reading as byte then convert it to hex or whatever you do but I'm ask If I have an hex string that represent a file is there any way to write this file again and open it ??? – BlackRoot Dec 01 '14 at 14:24
  • @BlackRoot: convert the hex string back to a byte stream and write that to a file: http://stackoverflow.com/questions/1467005/convert-a-hex-string-to-a-byte-in-java – cello Dec 01 '14 at 14:37
  • @cello I have a file that contains "test one test" string after reading file and get hex string and convert hex to byte and write it using this code `RandomAccessFile file = new RandomAccessFile("D:\\file.txt", "rw"); file.write(bytes); file.close();` I've got dummy charecters – BlackRoot Dec 01 '14 at 15:12

2 Answers2

2

Read File into Array of bytes and convert it to Hex

StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                result.append(String.format("%02x", b));
            }
 result.toString();

Make any modification to hex then save it again using this method

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                + Character.digit(s.charAt(i + 1), 16));
    }
    return data;
}

This Method return an Array of byte so you can write these bytes using this code

RandomAccessFile file = new RandomAccessFile([Any file Name with extention], "rw");

file.write(bytes);

file.close();
BlackRoot
  • 504
  • 1
  • 9
  • 29
-1

use the format() method.

Read your file as bytes and then convert it to bytes.

String.format("%02x", byteFromFile);

Iterate it until all bytes are read and then add it to a StringBuilder

StringBuilder hexbyteString;

for(byte myfile : filebyte) {
        hexbyteString.append(String.format("%02x", myfile));
    }
    return hexbyteString.toString();
BDRSuite
  • 1,594
  • 1
  • 10
  • 15