How to convert string to byte[] with same content - java

I want to convert string to byte[] with same content. Example
I have:
String str = "abc";
byte[] bytes;
//I want to convert "str" to "bytes" that they have same content:
(code here)
//after, print bytes -> "abc".

With a little effort, you'd reach this.
So what we do is use the getBytes method
byte[] convertToBytes= stuff.getBytes("UTF-8");
String newString = new String(convertToBytes, "UTF-8");
source
Converting a set of strings to a byte[] array
Also study up on the String API page

String str = "abc";
byte bytes[] = str.getBytes(); // Get the byte array
for (byte b : bytes) {
System.out.println("Byte is "+b); //Iterate and print
}
str = new String(bytes); // Create String from byte array
System.out.println("String is "+str);

Related

Read and convert binary file to char file using Java

I'm trying to read a shortcod-file binary file that could be found here.
The method i'm using to print the content of this file:
public void read3RegularGraphs( String pathFile ) throws IOException {
InputStream reader = new FileInputStream(pathFile);
byte [] fileBytes = Files.readAllBytes(new File(pathFile).toPath());
char singleChar;
for(byte b : fileBytes) {
singleChar = (char) b;
System.out.print(singleChar);
}
}
Unfortunatly, I'm getting an incorrect output format, i'm getting symbols in place of chars.
How can I convert the binary content to character format.
Thank you
You need to pass Charset to use decoding. Char and byte are two different things
List<String> stringList = Files.readAllLines(new File(pathFile).toPath(), Charset.forName("UTF-8"));
When you convert among Char, Strings and byte arrays, declare explicitly the Charset
byte[] byteArray= stringTest.getBytes(Charset.forName("UTF-8"));
String stringTest = new String(byteArray, Charset.forName("UTF-8"));

Convert int array of byte to String in JAVA

i have following problem:
i have array of 2 int - its char ř how can i convert this array to string or char?
real values in array are: [-59, -103]
ř->[-59, -103]->ř
Thank you.
EDIT:
String specialChar = "ř";
System.out.println(specialChar);
byte[] tmp = specialChar.getBytes();
System.out.println(Arrays.toString(tmp)); //[-59, -103]
int[] byteIntArray = new int[2];
byteIntArray[0] = (int) tmp[0];
byteIntArray[1] = (int) tmp[1];
System.out.println(Arrays.toString(byteIntArray)); //[-59, -103]
//now i want convert byteIntArray to string
What about that?
byte[] byteArray = new byte[2];
byteArray[0] = (byte)byteIntArray[0];
byteArray[1] = (byte)byteIntArray[1];
String specialChar = new String(byteArray);
Note that String.getBytes() uses your local platform encoding to convert the string into a byte array. So the resulting byte array depends on your individual system settings.
If you want your byte array to be compatible to other systems, use a standard encoding like "UTF-8" instead:
byte[] tmp = specialChar.getBytes("UTF-8"); // String -> bytes
String s = new String(tmp, "UTF-8"); // bytes -> String

Converting byte array containing ASCII characters to a String

I have a byte array that consists of ASCII characters that I wish to convert to a String. For example:
byte[] myByteArray = new byte[8];
for (int i=0; i<8; i++) {
byte[i] = (byte) ('0' + i);
}
myByteArray should contain a string "12345678" after the loop. How do I get this string into a String variable?
Thanks!
Use
new String(myByteArray, "UTF-8");
String class provides a constructor for this.
Side note:The second argument here is the CharSet(byte encoding) which should be handled carefully. More here.
String aString = new String(yourByteArray);
or
String aString = new String(yourByteArray, "aCharSet");
//Replacing "aCharSet" with the appropriate chararacter set
Easy See docs

Converting bytearray output to string without value changing in java

I have a byte[] array named byteval in java and if I do System.out.println(byteval), I can read: d3e1547c254ff7cec8dbcef2262b5cf10ec079c7[B#40d150e0
Now I need this what I read there as a string, but if I try to convert it with Byte.toString or a new string constuctor, the value is not the same, most there are some numbers instead.
So how can I get the byte[] array as a String called strval, also cutting off the [B#40d150e0?
Now: System.out.println(byteval)>> d3e1547c254ff7cec8dbcef2262b5cf10ec079c7[B#40d150e0
Goal: System.out.println(strval)>> d3e1547c254ff7cec8dbcef2262b5cf10ec079c7
Lot of thanks!
Danny
EDIT: Working solution for me:
byte[] byteval = getValue();
// Here System.out.println(byteval) is
// d3e1547c254ff7cec8dbcef2262b5cf10ec079c7[B#40d150e0
BigInteger bi = new BigInteger(1, byteval);
String strval = bi.toString(16);
if ((strval.length() % 2) != 0) {
strval = "0" + strval;
}
System.out.println(strval);
// Here the String output is
// d3e1547c254ff7cec8dbcef2262b5cf10ec079c7
Thank all answerer.
just do
System.out.println(byteval.toString())
instead of
System.out.println(byteval)
this will remove the ending part(Actually that is just the address of the object referenced)
Try this:
String str= new String(byteval, "ISO-8859-1");
System.out.println(str);

Issue Decoding for a specific charset

I'm trying to decode a char and get back the same char.
Following is my simple test.
I'm confused, If i have to encode or decode. Tried both. Both print the same result.
Any suggestions are greatly helpful.
char inpData = '†';
String str = Character.toString((char) inpData);
byte b[] = str.getBytes(Charset.forName("MacRoman"));
System.out.println(b[0]); // prints -96
String decData = Integer.toString(b[0]);
CharsetDecoder decoder = Charset.forName("MacRoman").newDecoder();
ByteBuffer inBuffer = ByteBuffer.wrap(decData.getBytes());
CharBuffer result = decoder.decode(inBuffer);
System.out.println(result.toString()); // prints -96, expecting to print †
CharsetEncoder encoder = Charset.forName("MacRoman").newEncoder();
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(decData));
result = decoder.decode(bbuf);
System.out.println(result.toString());// prints -96, expecting to print †
Thank you.
When you do String decData = Integer.toString(b[0]);, you create the string "-96" and that is the string you're encoding/decoding. Not the original char.
You have to change your String back to a byte before.
To get your character back as a char from the -96 you have to do this :
String string = new String(b, "MacRoman");
char specialChar = string.charAt(0);
With this your reversing your first transformation from char -> String -> byte[0] by doing byte[0] -> String -> char[0]
If you have the String "-96", you must change first your string into a byte with :
byte b = Byte.parseByte("-96");
String decData = Integer.toString(b[0]);
This probably gets you the "-96" output in the last two examples. try
String decData = new String(b, "MacRoman");
Apart from that, keep in mind that System.out.println uses your system-charset to print out strings anyway. For a better test, consider writing your Strings to a file using your specific charset with something like
FileOutputStream fos = new FileOutputStream("test.txt");
OutputStreamWriter writer = new OutputStreamWriter(fos, "MacRoman");
writer.write(result.toString());
writer.close();

Categories

Resources