I wish to convert a byte array to String but as I do so, my String has 00 before every digit got from the array.
I should have got the following result: 49443a3c3532333437342e313533373936313835323237382e303e
But I have the following:
Please help me, how can I get the nulls away?
I have tried the following ways to convert:
xxxxId is the byteArray
String xxxIdString = new String(Hex.encodeHex(xxxxId));
Thank you!
Try something like this:
String s = new String(bytes);
s = s.replace("\0", "")
It's also posible, that the string will end after the first '\0' received, if thats the case, first iterate through the array and replace '\0' with something like '\n' and do this:
String s = new String(bytes);
s = s.replace("\n", "")
EDIT:
use this for a BYTE-ARRAY:
String s = new String(bytes, StandardCharsets.UTF_8);
use this for a CHAR:
String s = new String(bytes);
Try below code:
byte[] bytes = {...}
String str = new String(bytes, "UTF-8"); // for UTF-8 encoding
please have a look here- How to convert byte array to string and vice versa?
In order to convert Byte array into String format correctly, we have to explicitly create a String object and assign the Byte array to it.
String example = "This is an example";
byte[] bytes = example.getBytes();
String s = new String(bytes);
Related
I have a constraint: I cannot save some chars (like & and =) in a some special storage.
The problem is that I have strings (user input) that contain these not allowed special chars, which I'd like to save to that storage .
I'd like to convert such string to another string that wouldn't contain these special characters.
I'd like to still be able to convert back to the original string without creating ambiguity.
Any idea how to implement the de/convert? Thanks.
Convert the user input to Hex and save. And convert the hex value back to string. Use these methods.
public static String stringToHex(String arg) {
return String.format("%x", new BigInteger(1, arg.getBytes(Charset.forName("UTF-8"))));
}
public static String hexToString(String arg) {
byte[] bytes = DatatypeConverter.parseHexBinary(arg);
return new String(bytes, Charset.forName("UTF-8"));
}
Usage:
String h = stringToHex("Perera & Sons");
System.out.println(h);
System.out.println(hexToString(h));
OUTPUT
506572657261202620536f6e73
Perera & Sons
Already pointed out in the comments but URL Encoding looks like the way to go.
In Java done simply URLEncoder and URLDecoder
String encoded = URLEncoder.encode("My string &with& illegal = characters ", "UTF-8");
System.out.println("Encoded String:" + encoded);
String decoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println("Decoded String:" + decoded);
URLEncoder
URLDecoder
Welcome,
I have a byte[] which is the binary representation of a String. And I wanted to replace a part of this String and get back the new byte[]!
I have tried:
String string = new String(array);
string = string.replace("#+#","SOME STRING");
array = string.getBytes();
The problem is that array is that the array afterwards is something different and not only because of the replacement.
The content of the array are serialized objects seperated with "#+#".
Be explicit about the character encoding you are using and use an encoding such as "Latin-1" where all byte sequences map to valid Unicode characters:
String string = new String(array, "Latin-1");
string = string.replace("#+#","SOME STRING");
array = string.getBytes("Latin-1");
I tried to decode a string to byte array using Base64. But it returned null. Here is the code:
LZW lzw = new LZW();
String enkripEmbedFileString = Base64.encode(byteFile);
List<Short> compressed = lzw.compress(enkripEmbedFileString);
String kompress = "";
Iterator<Short> compressIterator = compressed.iterator();
while (compressIterator.hasNext()) {
String sch = compressIterator.next().toString();
int in = Integer.parseInt(sch);
char ch = (char) in;
kompress = kompress + ch;
}
byteFile = Base64.decode(kompress);
I call "byteFile" variable at the last row in a code below this code and it throw NullPointerException.
I have check the "kompress" variable and it's not null. It contains a string.
All you need to know is, with that code I compress a string with LZW which require String for parameter and returns List<Short>. And, I convert the List<Short> to a String with a loop that you can see.
The problem is, why Base64 failed to convert String to byte[], after that String modified with LZW?
Whereas, if I decompress the String first and than return the decompressed String to be converted with Base64 to byte[], has no problem. It works. Here is the code which works:
//LZW Compress
LZW lzw = new LZW();
String enkripEmbedFileString = Base64.encode(byteFile);
List<Short> compressed = lzw.compress(enkripEmbedFileString);
String kompress = "";
Iterator<Short> compressIterator = compressed.iterator();
while (compressIterator.hasNext()) {
String sch = compressIterator.next().toString();
int in = Integer.parseInt(sch);
char ch = (char) in;
kompress = kompress + ch;
}
//Decompress
List<Short> kompressback = back(kompress);
String decompressed = decompress(kompressback);
byteFile = Base64.decode(decompressed);
Please, give me an explanation. Where is my fault?
Base64 decode can be applied only to strings that contain Base64 encoded data. Since you encode and then compress, the result is not Base64. You proved it yourself when you saw that uncompressing the data first allowed you to then decode the Base64 string.
When I got JSON then there are \u003c and \u003e instead of < and >. I want to convert them back to utf-8 in java. any help will be highly appreciated. Thanks.
try {
// Convert from Unicode to UTF-8
String string = "\u003c";
byte[] utf8 = string.getBytes("UTF-8");
// Convert from UTF-8 to Unicode
string = new String(utf8, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
refer http://www.exampledepot.com/egs/java.lang/unicodetoutf8.html
You can try converting the string into a byte array
byte[] utfString = str.getBytes("UTF-8") ;
and convert that back to a string object by specifying the UTF-8 encoding like
str = new String(utfString,"UTF-8") ;
You can also try this
String s = "Hello World!";
String convertedInUTF8 = new String(s, StandardCharsets.US_ASCII);
I have a string cityName which I decoded into bytes as follows:
byte[] cityBytes = cityName.getBytes("UTF-8");
...and stored the bytes somewhere. When I retrieve those bytes, how can I decode them back into a string?
Use the String(byte[], Charset) or String(byte[], String) constructor.
byte[] rawBytes = /* whatevs */
try
{
String decoded = new String(rawBytes, Charset.forName("UTF-8"));
// or
String decoded = new String(rawBytes, "UTF-8");
// best, if you're using Java 7 (thanks to #ColinD):
String decoded = new String(rawBytes, StandardCharsets.UTF_8);
}
catch (UnsupportedEncodingException e)
{
// see http://stackoverflow.com/a/6030187/139010
throw new AssertionError("UTF-8 not supported");
}
The String class has a few constructors that accept an array of bytes, including one that takes an array of bytes and a String representation of a charset and another that takes a Charset object. There are also constructors that take the offset and length of the String as arguments, if the String is only a small section of the byte array.
Like this:
String cityName = new String(cityByte,"UTF-8");
String s = new String(cityByte, "UTF-8");
Try this: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
String(byte[] bytes, String charsetName)