Convert String.getBytes[].toString To byte[] [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a problem converting strings to bytes. My problem is this:
String hello = "hello";
byte[] bytes = hello.getBytes();
String byteString = bytes.toString();
Now I want to convert this string to byte[].
and finally get "hello"
Thank you for your help

When you need byte[] to String, use new String(yourArray)
When you need String to byte[], use yourString.getBytes()
String hello = "hello";
byte[] bytes = hello.getBytes();
String byteString = new String(bytes);
System.out.println("byteString: " + byteString); // byteString: hello
byte[] newArray = byteString.getBytes();
String otherString = new String(newArray);
System.out.println("otherString: " + otherString); // otherString: hello
The "toString()" of byte array is the "toString()" inheritance from Object.
The method is:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So, it is the reason for... if you call: yourArray.toString() returns something like [B#dcf3e99

I got the answers to my questions. Thank you all for the tips and even those who gave negative feedback to my questions.
The best way to send a string in bytes and get it in bytes is to encode to base64 and get the decode on the other side.
String hello = "hello";
byte[] bytes = hello.getBytes();
String encode = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(bytes );
byte[] decode = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(encode);
System.out.println(new String(decode));
I solved my problem this way, I hope it will be useful for someone who has encountered this problem.
Thanks everyone

Related

Converting byte array to String Java

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);

String to byte[] and byte[] to String [duplicate]

This question already has answers here:
How to convert String into Byte and Back
(2 answers)
How do you convert binary data to Strings and back in Java?
(4 answers)
Closed 7 years ago.
I'm dealing with some code that converts a String into a byte[], then from byte[] to String (a String which is a binary representation of the original String), then I'm supposing to do something with that String. When I try to convert the String to byte[] and byte[] to the original String, something is not working.
byte[] binary = "Example".getBytes(StandardCharsets.UTF_8);
String x = new String();
for(byte b : binary)
{
x += Integer.toBinaryString(b);
}
byte[] b = new byte[x.length()];
for (int i = 0; i < b.length; i++)
{
b[i] = (byte) (x.charAt(i) - '0');
}
String str = new String(b, StandardCharsets.UTF_8);
System.out.println(str);
As you can see in that code, I'm using an example String called "Example" and I'm trying to do what I wrote above.
When I print str, I'm not getting that "Example" string.
Does anyone know a way to do this? I searched for a solution on Stack Overflow itself, but I can't figure out a solution.
This should work without the middle section.
byte[] binary = "Example".getBytes(StandardCharsets.UTF_8);
String str = new String(binary, StandardCharsets.UTF_8);
System.out.println(str);

Find a String and return the words after it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have this method which receive as parameters pdfText(which is a String containing text from a pdf file after parsing) and fileName which is the file where i want to write that text
But now I need to find the word "Keywords" in this text and extract only the words after it,which are in the same line(until the newline character).
For example I have one text which contains somewhere the following line
Title:Something.
"Keywords : Computers, Robots, Course"
Tags:tag1,tag2,tag3.
And the result should be the following list ["Computers","Robots", "Course"].
Solved Question
So I've searched how to solve my question..here is a solution,not very smart but it works:
//index of first appearence of the word
int index = pdfText.indexOf("Keywords");
//string from that to the end
String subStr = pdfText.substring(index);
//index of first appearence of the new line in the new string
int index1 = subStr.indexOf("\n");
//the string we need
String theString = subStr.substring(9,index1);
System.out.println(theString);
//write in the file..use true as parameter for appending text,not overwrite it
FileWriter pw = new FileWriter(fileName,true);
pw.write(theString);
pw.close();
Honestly, this question is too situation specific. Regardless :)
Writing to file
String pdfText = "pdfText";
String fileLocation = "fileLocation";
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileLocation), "utf-8"));
writer.write(pdfText); // String you want to write (i.e. pdfText)
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {writer.close();} catch (Exception ex) { ex.printStackTrace(); }
}
It's always a good idea to specify the encoding type. ("utf-8"). It might not matter for your assignment though. You might also need to append to the file, and not re-write it completely, in which case, you should use a different constructor for the FileOutputStream, new FileOutputStream(getFileLocation(), true) . As for the many try/catch blocks, don't follow my example. It's how I manage to close my resource, as eclipse recommends haha.
Parsing the String
If you have a line such as "Keywords : Computers, Robots, Course",
String str = "Keywords : Computers, Robots, Course";
String[] array = str.substring(indexOf(':') + 1).split(",");
//this array = ["Computers", "Robots", "Course"]
Now you have an array which you can loop through and write/print out however you'd like.
You could use regex to extract the words after the word "Keyword:" like this :
String regex = ".*Keywords\\s*:(.*)\\n.*";
String extractedLine = yourText.replaceAll( regex, "$1" );
System.out.println( extractedLine );

How to Convert a String value to Binary String in java [duplicate]

This question already has answers here:
Convert A String (like testing123) To Binary In Java [closed]
(10 answers)
Closed 9 years ago.
I need to convert a String value into Binary format.
For Example:
String str = "Java";
now i want to get it in binary format.how could i do this?
any one could please help me!
Thanks in advane
Try this,
byte[] infoBin = null;
infoBin = "Java".getBytes("UTF-8");
for (byte b : infoBin) {
System.out.println("c:" + (char) b + "-> "
+ Integer.toBinaryString(b));
}
See this link : String to binary output in Java
Try this
byte[] bytes = str.getBytes(charSetName);
this encodes str into a sequence of bytes using the named charset, storing the result into a byte array.
string have getBytes() method.
str.getBytes();
following will give you byte code;
String str = "Java";
byte[] bytecode=str.getBytes();

Convert from byte array to string and string to byte array in java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Conversion of byte[] into a String and then back to a byte[]
I have the following piece of code, I'm trying to get the test to pass, but can't seem to get my head around the various forms of encoding that go on in the java world.
import java.util.Arrays;
class Test {
static final byte[] A = { (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66, (byte)0x77, (byte)0x88, (byte)0x99, (byte)0x00, (byte)0xAA };
public static void main(String[] args) {
String s = new String(A);
byte[] b = s.getBytes();
if (Arrays.equals(A,b)) {
System.out.println("TEST PASSED!");
}
else {
System.out.println("TEST FAILED!");
}
}
}
I guess my question is: What is the correct way to convert a byte array of arbitary bytes to a Java String, then later on convert that same Java String to another byte array, which will have the same length and same contents as the original byte array?
Try a specific encoding:
String s = new String(A, "ISO-8859-1");
byte[] b = s.getBytes("ISO-8859-1");
ideone link
Use Base64.
Apache Commons Codec has a Base64 class which supports the following interface:
String str = Base64.encodeBase64String(bytes);
byte[] newBytes = Base64.decodeBase64(str);

Categories