0

I got a byte array string of a file and would like every byte to be taken minus 2 or something like that, and later to be taken plus 2. I wanted to do it like this:

byte buffer[] = new byte[(int) file.length()];
try {
    in = new FileInputStream(file);
    in.read(buffer);

    for(int i = 0; i < buffer.length; i++){
        buffer[i] = (byte) (buffer[i]-2); // and then later +2
    }
}

But it doesn't work. First it changes the file like I want to, but later when I take the whole thing +2 it gives me something else strange.

So all together I want this:

  1. Get a byte array called buffer
  2. Then change some values
  3. Change these values back
  4. Get the same files as before
Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
Henry Mü
  • 91
  • 6
  • Try using a debugger to inspect the byte array before and after your manipulations. This will tell you if it is an algorithm problem or an I/O problem. – Kevin K Jan 11 '13 at 19:43

2 Answers2

2

There are some errors in your code:

  1. new byte[(int) file.length()]; This will definitive lead into an OutOfMemoryError or a corrupt read of the file
  2. in.read(buffer); This will only read some bytes of your file.
  3. You tagged this question with "encryption". This is no encryption at all. It will be really easy to "decrypt" the content.

Is your file still the same length?

Christian Kuetbach
  • 15,850
  • 5
  • 43
  • 79
1

You need to use the return value of the in.read() call to know exactly how many bytes were actually read into the buffer, and thus how many bytes to write to your output.

David R Tribble
  • 11,918
  • 5
  • 42
  • 52