Naive approach:
You can iterate through an array of bytes:
final byte[] bytes = "FooBar".getBytes(); for (byte b : bytes) { System.out.print(b + " "); }
Result: 70 111 111 66 97 114
or through a char array and convert char to a primitive int
for (final char c : "FooBar".toCharArray()) { System.out.print((int) c + " "); }
Result: 70 111 111 66 97 114
or, thanks to Java8, using forEach via inputSteam: "FooBar".chars().forEach(c -> System.out.print(c + " "));
Result: 70 111 111 66 97 114
or, thanks to Java8 and Apache Commons Lang : final List<Byte> list = Arrays.asList(ArrayUtils.toObject("FooBar".getBytes())); list.forEach(b -> System.out.print(b + " "));
final List<Byte> list = Arrays.asList(ArrayUtils.toObject("FooBar".getBytes())); list.forEach(b -> System.out.print(b + " "));
Result: 70 111 111 66 97 114
Better to use charset (ASCII, UTF-8, ...):
// Convert a String to byte array (byte[]) final String str = "FooBar"; final byte[] arrayUtf8 = str.getBytes("UTF-8"); for(final byte b: arrayUtf8){ System.out.println(b + " "); }
Result: 70 111 111 66 97 114
final byte[] arrayUtf16 = str.getBytes("UTF-16BE"); for(final byte b: arrayUtf16){ System.out.println(b); }
Result: 70 0 111 0 111 0 66 0 97 0 114
Hope this helps.
source share