Skip to content
Advertisement

Gibberish at the end of a String byte array passed to native code

I am writing an applet to wrap a proprietary .dll that can be used in the browser. To achieve this, I am using JNA. The .dll connects to a check scanner peripheral, and can pull images from the devices memory.

I have to make a Windows API call in Java, using JNA, to get the image:

// DEVICE is the JNA Library interface

HANDLEByReference img = new HANDLEByReference();
File outfile = new File("my_image.bmp");

DEVICE.saveImage(img.getValue(), outfile.getName().getBytes());

When the code saves the image, I get one named something like:

C:UsersuserworkspaceJavaProjectbinmy_image.bmpó_¯=Pá

note the gibberish at the end

Does Java return a NULL terminated byte[] array when calling getBytes() on a String?

Advertisement

Answer

No, String.getBytes() just returns the bytes in the encoded form of the string.

Note that it also uses the platform default encoding unless you specify the encoding, and that default may not be what you want.

If you want an array with a “0” byte at the end, you could use:

byte[] data = outfile.getName().getBytes(encoding);
byte[] padded = new byte[data.length + 1];
System.arraycopy(data, 0, padded, 0, data.length);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement