How better use replaceAll? - java

String jparse = [[10, 20, 'stringone', '{gvdfdf}'], [12, 30, 'stringtwo', '{vxcbnn}']]
How use replace all, that result was: [{gvdfdf}, {vxcbnn}]

I get answer to my question. Maybe this answer will help someone.
String jparse = [[10, 20, 'stringone', '{gvdfdf}'], [12, 30, 'stringtwo', '{vxcbnn}']]
String b = jparse.replaceAll("\\[\\d*, \\d*, '\\w*', '(\\{\\w+\\})'\\]", "$1");

Related

Java get string from byte array

I am modding a java program and in it a handler receives 2 byte arrays
When I print those arrays using a line of code like this\
java.util.Arrays.toString(this.part1))
I get an output like this
[43, 83, 123, 97, 104, -10, -4, 124, -113, -56, 118, -23, -25, -13, -9, -85, 58, -66, -34, 38, -55, -28, -40, 125, 22, -83, -72, -93, 73, -117, -59, 72, 105, -17, 3, -53, 121, -21, -19, 103, 101, -71, 54, 37...
I know these byte arrays contain a string. How might I get that string from them?
Here is the code
public void readPacketData(PacketBuffer data) throws IOException
{
this.field_149302_a = data.readByteArray();
this.field_149301_b = data.readByteArray();
String packet1 = (java.util.Arrays.toString(this.field_149302_a));
String packet2 = (java.util.Arrays.toString(this.field_149301_b));
}
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. You can try this:
String str = new String(this.part1, "UTF-8"); //for UTF-8 encoding
System.out.println(str);
Please note that the byte array contains characters in a special encoding (that you must know).
String has a constructor from byte[], so you could just call new String(this.part1), or, if the bytes do not represent a string in the platform's default charster, use the overloaded flavor and pass the charset too.
actually to convert bytes to String you need encoding name. You need to change UTF-8 to correct encoding name in first answer to avoid wrong output, try UTF-16 or one of https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html (try to choose by your locale).

How do I print out string values stored in an Array?

I am using Java on NetBeans 8. I have searched google and other stack overflow questions but I cannot find anything that relates to my question. Also, I have consulted the oracle documentation and their example gave me the same error I am experiencing.
I would like the array string values below to print out to the output box using a line of code like:
System.out.println(pbArray[0][0] + pbArray[1][0]);
////////////////////////////////////////////////
But no matter where I try to input that line of code I cannot make it work. NetBeans tells me there is "an identifier expected."
package com.mnlottery.console;
public class ComMnlotteryConsole {
public static void main(String[] args) {
class powerball{
String[][] pbArray = {
{"August 16th, 2014","August 13th, 2014","August 9th, 2014"},
{"07, 08, 17, 48, 69, 09, $50,000,000","08, 37, 39, 40, 52, 24,"
+ " $40,000,000","03, 12, 31, 34, 51, 24, 90,000,000"}};
}
}
}
I feel like this should be fairly simple. Thanks in advance.
I think you wanted (no inner class)
public static void main(String[] args) {
String[][] pbArray = {
{ "August 16th, 2014", "August 13th, 2014", "August 9th, 2014" },
{ "07, 08, 17, 48, 69, 09, $50,000,000",
"08, 37, 39, 40, 52, 24," + " $40,000,000",
"03, 12, 31, 34, 51, 24, 90,000,000" } };
System.out.println(pbArray[0][0] + pbArray[1][0]);
}
But, you can print the array(s) in a few ways,
Arrays.deepToString(Object[])
A loop, and Arrays.toString(Object[])
like
String[][] pbArray = {
{ "August 16th, 2014", "August 13th, 2014", "August 9th, 2014" },
{ "07, 08, 17, 48, 69, 09, $50,000,000",
"08, 37, 39, 40, 52, 24," + " $40,000,000",
"03, 12, 31, 34, 51, 24, 90,000,000" } };
// 1.
System.out.println(Arrays.deepToString(pbArray));
// or 2.
for (String [] arr : pbArray) {
System.out.println(Arrays.toString(arr));
}
Change System.out.println(pbarray[0][0] + names[1][0]); to
System.out.println(pbArray[0][0] + pbArray[1][0]);
names and pbarray do not exist. pbArray is the correct identifier.

What does MessageDigest.update(byte[]) do?

What exactly does this do? I tried to look it up but didn't find anything.
Reason for asking is I want to incorporate a SALT byte[] into a value which is then hashed. So should it be done like this (Pseudo code):
MessageDigest.update(SALT);
MessageDigest.update(value);
digestValue = MessageDigest.digest();
// Where SALT, value and digestValue are array bytes, byte[]
Does this add both SALT and value to the final digest or should I combine both variables into one and then update it once?
I couldn't find an answer for this in any documentation, any clarification would be appreciated.
Thank you, cheers.
MessageDigest is statefull, calls of MessageDigest.update(byte[] input) accumulate digest updates until we call MessageDigest.digest. Run this test to make sure:
MessageDigest md1 = MessageDigest.getInstance("MD5");
md1.update(new byte[] {1, 2});
md1.update(new byte[] {3, 4});
System.out.println(Arrays.toString(md1.digest()));
MessageDigest md2 = MessageDigest.getInstance("MD5");
md2.update(new byte[] {1, 2, 3, 4});
System.out.println(Arrays.toString(md2.digest()));
output
[8, -42, -64, 90, 33, 81, 42, 121, -95, -33, -21, -99, 42, -113, 38, 47]
[8, -42, -64, 90, 33, 81, 42, 121, -95, -33, -21, -99, 42, -113, 38, 47]

I get different results reading the same file from the file system and from inside a jar

I have a file that my Java application takes as input which I read 6 bytes at a time. When I read it in off the file system everything works fine. If I build everything into a jar the first 4868 reads work fine, but after that it starts returning the byte arrays in the wrong order and also ends up having read more data at the end.
Here is a simplified version of my code which reproduces the problem:
InputStream inputStream = this.getClass().getResourceAsStream(filePath);
byte[] byteArray = new byte[6];
int counter = 0;
while ((inputStream.read(byteArray) != -1))
{
counter++;
System.out.println("Read #" + counter +": " + Arrays.toString(byteArray));
}
System.out.println("Done.");
This is the [abbreviated] output I get when reading off of the file system:
...
Read #4867: [5, 0, 57, 7, 113, -26]
Read #4868: [2, 0, 62, 7, 114, -26]
Read #4869: [2, 0, 68, 7, 115, -26]
Read #4870: [3, 0, 75, 7, 116, -26]
Read #4871: [2, 0, 83, 7, 117, -26]
...
Read #219687: [1, 0, 4, -8, 67, 33]
Read #219688: [1, 0, 2, -8, 68, 33]
Read #219689: [5, 0, 1, -8, 67, 33]
Done.
And here is what I get reading from a jar:
...
Read #4867: [5, 0, 57, 7, 113, -26]
Read #4868: [2, 0, 62, 7, 113, -26] //everything is fine up to this point
Read #4869: [7, 114, -26, 2, 0, 68]
Read #4870: [7, 115, -26, 3, 0, 75]
Read #4871: [7, 116, -26, 2, 0, 83]
...
Read #219687: [95, 33, 1, 0, 78, -8]
Read #219688: [94, 33, 1, 0, 76, -8]
Read #219689: [95, 33, 1, 0, 74, -8]
...
Read #219723: [67, 33, 1, 0, 2, -8]
Read #219724: [68, 33, 5, 0, 1, -8]
Read #219725: [67, 33, 5, 0, 1, -8]
Done.
I unzipped the jar and confirmed that the files being read are identical, so what could cause the reader to return different results?
Your reading loop is wrong.
inputStream.read() method returns number of bytes it really read. You have to check this number before transforming the data into string.
When you are reading from file the bytes are not arrived all together. At one of the iterations of your loop you probably read 4 of expected 6 bytes, so your transformation to string does not work.
If you are reading integers I'd recommend you to wrap your raw input string using Scanner or good old DataInputStream and read integers directly.

Java Byte Array to String to Byte Array

I'm trying to understand a byte[] to string, string representation of byte[] to byte[] conversion... I convert my byte[] to a string to send, I then expect my web service (written in python) to echo the data straight back to the client.
When I send the data from my Java application...
Arrays.toString(data.toByteArray())
Bytes to send..
[B#405217f8
Send (This is the result of Arrays.toString() which should be a string representation of my byte data, this data will be sent across the wire):
[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]
On the python side, the python server returns a string to the caller (which I can see is the same as the string I sent to the server
[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]
The server should return this data to the client, where it can be verified.
The response my client receives (as a string) looks like
[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]
I can't seem to figure out how to get the received string back into a
byte[]
Whatever I seem to try I end up getting a byte array which looks as follows...
[91, 45, 52, 55, 44, 32, 49, 44, 32, 49, 54, 44, 32, 56, 52, 44, 32, 50, 44, 32, 49, 48, 49, 44, 32, 49, 49, 48, 44, 32, 56, 51, 44, 32, 49, 49, 49, 44, 32, 49, 48, 57, 44, 32, 49, 48, 49, 44, 32, 51, 50, 44, 32, 55, 56, 44, 32, 55, 48, 44, 32, 54, 55, 44, 32, 51, 50, 44, 32, 54, 56, 44, 32, 57, 55, 44, 32, 49, 49, 54, 44, 32, 57, 55, 93]
or I can get a byte representation which is as follows:
B#2a80d889
Both of these are different from my sent data... I'm sure Im missing something truly simple....
Any help?!
You can't just take the returned string and construct a string from it... it's not a byte[] data type anymore, it's already a string; you need to parse it. For example :
String response = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]"; // response from the Python script
String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];
for (int i=0, len=bytes.length; i<len; i++) {
bytes[i] = Byte.parseByte(byteValues[i].trim());
}
String str = new String(bytes);
** EDIT **
You get an hint of your problem in your question, where you say "Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ...", because 91 is the byte value for [, so [91, 45, ... is the byte array of the string "[-45, 1, 16, ..." string.
The method Arrays.toString() will return a String representation of the specified array; meaning that the returned value will not be a array anymore. For example :
byte[] b1 = new byte[] {97, 98, 99};
String s1 = Arrays.toString(b1);
String s2 = new String(b1);
System.out.println(s1); // -> "[97, 98, 99]"
System.out.println(s2); // -> "abc";
As you can see, s1 holds the string representation of the array b1, while s2 holds the string representation of the bytes contained in b1.
Now, in your problem, your server returns a string similar to s1, therefore to get the array representation back, you need the opposite constructor method. If s2.getBytes() is the opposite of new String(b1), you need to find the opposite of Arrays.toString(b1), thus the code I pasted in the first snippet of this answer.
String coolString = "cool string";
byte[] byteArray = coolString.getBytes();
String reconstitutedString = new String(byteArray);
System.out.println(reconstitutedString);
That outputs "cool string" to the console.
It's pretty darn easy.
What I did:
return to clients:
byte[] result = ****encrypted data****;
String str = Base64.encodeBase64String(result);
return str;
receive from clients:
byte[] bytes = Base64.decodeBase64(str);
your data will be transferred in this format:
OpfyN9paAouZ2Pw+gDgGsDWzjIphmaZbUyFx5oRIN1kkQ1tDbgoi84dRfklf1OZVdpAV7TonlTDHBOr93EXIEBoY1vuQnKXaG+CJyIfrCWbEENJ0gOVBr9W3OlFcGsZW5Cf9uirSmx/JLLxTrejZzbgq3lpToYc3vkyPy5Y/oFWYljy/3OcC/S458uZFOc/FfDqWGtT9pTUdxLDOwQ6EMe0oJBlMXm8J2tGnRja4F/aVHfQddha2nUMi6zlvAm8i9KnsWmQG//ok25EHDbrFBP2Ia/6Bx/SGS4skk/0couKwcPVXtTq8qpNh/aYK1mclg7TBKHfF+DHppwd30VULpA==
What Arrays.toString() does is create a string representation of each individual byte in your byteArray.
Please check the API documentation
Arrays API
To convert your response string back to the original byte array, you have to use split(",") or something and convert it into a collection and then convert each individual item in there to a byte to recreate your byte array.
Its simple to convert byte array to string and string back to byte array in java. we need to know when to use 'new' in the right way.
It can be done as follows:
byte array to string conversion:
byte[] bytes = initializeByteArray();
String str = new String(bytes);
String to byte array conversion:
String str = "Hello"
byte[] bytes = str.getBytes();
For more details, look at:
http://evverythingatonce.blogspot.in/2014/01/tech-talkbyte-array-and-string.html
The kind of output you are seeing from your byte array ([B#405217f8) is also an output for a zero length byte array (ie new byte[0]). It looks like this string is a reference to the array rather than a description of the contents of the array like we might expect from a regular collection's toString() method.
As with other respondents, I would point you to the String constructors that accept a byte[] parameter to construct a string from the contents of a byte array. You should be able to read raw bytes from a socket's InputStream if you want to obtain bytes from a TCP connection.
If you have already read those bytes as a String (using an InputStreamReader), then, the string can be converted to bytes using the getBytes() function. Be sure to pass in your desired character set to both the String constructor and getBytes() functions, and this will only work if the byte data can be converted to characters by the InputStreamReader.
If you want to deal with raw bytes you should really avoid using this stream reader layer.
Can you not just send the bytes as bytes, or convert each byte to a character and send as a string? Doing it like you are will take up a minimum of 85 characters in the string, when you only have 11 bytes to send. You could create a string representation of the bytes, so it'd be "[B#405217f8", which can easily be converted to a bytes or bytearray object in Python. Failing that, you could represent them as a series of hexadecimal digits ("5b42403430353231376638") taking up 22 characters, which could be easily decoded on the Python side using binascii.unhexlify().
[JDK8]
import java.util.Base64;
To string:
String str = Base64.getEncoder().encode(new byte[]{ -47, 1, 16, ... });
To byte array:
byte[] bytes = Base64.getDecoder().decode("JVBERi0xLjQKMyAwIG9iago8P...");
If you want to convert the string back into a byte array you will need to use String.getBytes() (or equivalent Python function) and this will allow you print out the original byte array.
Use the below code API to convert bytecode as string to Byte array.
byte[] byteArray = DatatypeConverter.parseBase64Binary("JVBERi0xLjQKMyAwIG9iago8P...");
[JAVA 8]
import java.util.Base64;
String dummy= "dummy string";
byte[] byteArray = dummy.getBytes();
byte[] salt = new byte[]{ -47, 1, 16, ... }
String encoded = Base64.getEncoder().encodeToString(salt);
You can do the following to convert byte array to string and then convert that string to byte array:
// 1. convert byte array to string and then string to byte array
// convert byte array to string
byte[] by_original = {0, 1, -2, 3, -4, -5, 6};
String str1 = Arrays.toString(by_original);
System.out.println(str1); // output: [0, 1, -2, 3, -4, -5, 6]
// convert string to byte array
String newString = str1.substring(1, str1.length()-1);
String[] stringArray = newString.split(", ");
byte[] by_new = new byte[stringArray.length];
for(int i=0; i<stringArray.length; i++) {
by_new[i] = (byte) Integer.parseInt(stringArray[i]);
}
System.out.println(Arrays.toString(by_new)); // output: [0, 1, -2, 3, -4, -5, 6]
But to convert the string to byte array and then convert that byte array to string, below approach can be used:
// 2. convert string to byte array and then byte array to string
// convert string to byte array
String str2 = "[0, 1, -2, 3, -4, -5, 6]";
byte[] byteStr2 = str2.getBytes(StandardCharsets.UTF_8);
// Now byteStr2 is [91, 48, 44, 32, 49, 44, 32, 45, 50, 44, 32, 51, 44, 32, 45, 52, 44, 32, 45, 53, 44, 32, 54, 93]
// convert byte array to string
System.out.println(new String(byteStr2, StandardCharsets.UTF_8)); // output: [0, 1, -2, 3, -4, -5, 6]
I have also answered the same in the following question:
https://stackoverflow.com/a/70486387/17364272

Categories