vorrei trattare questo come un problema di serializzazione e giusto implementato come segue (codice Java completo e funzionante):
import java.nio.ByteBuffer;
import java.util.ArrayList;
public class Serialization {
public static byte[] serialize(String[] strs) {
ArrayList<Byte> byteList = new ArrayList<Byte>();
for (String str: strs) {
int len = str.getBytes().length;
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(len);
byte[] lenArray = bb.array();
for (byte b: lenArray) {
byteList.add(b);
}
byte[] strArray = str.getBytes();
for (byte b: strArray) {
byteList.add(b);
}
}
byte[] result = new byte[byteList.size()];
for (int i=0; i<byteList.size(); i++) {
result[i] = byteList.get(i);
}
return result;
}
public static String[] unserialize(byte[] bytes) {
ArrayList<String> strList = new ArrayList<String>();
for (int i=0; i< bytes.length;) {
byte[] lenArray = new byte[4];
for (int j=i; j<i+4; j++) {
lenArray[j-i] = bytes[j];
}
ByteBuffer wrapped = ByteBuffer.wrap(lenArray);
int len = wrapped.getInt();
byte[] strArray = new byte[len];
for (int k=i+4; k<i+4+len; k++) {
strArray[k-i-4] = bytes[k];
}
strList.add(new String(strArray));
i += 4+len;
}
return strList.toArray(new String[strList.size()]);
}
public static void main(String[] args) {
String[] input = {"This is","a serialization problem;","string concatenation will do as well","in some cases."};
byte[] byteArray = serialize(input);
String[] output = unserialize(byteArray);
for (String str: output) {
System.out.println(str);
}
}
}
l'idea è che nel campo di byte risultante abbiamo memorizzare la lunghezza della prima stringa (che è sempre 4 byte se si usa il digitare int
), seguito dai byte della prima stringa (la cui lunghezza può essere letta successivamente dai precedenti 4 byte), seguita dalla lunghezza della seconda stringa e dai byte della seconda stringa, e così via. In questo modo, l'array di stringhe può essere facilmente recuperato dall'array di byte risultante, come dimostrato dal codice precedente. E questo approccio di serializzazione può gestire qualsiasi situazione.
E il codice può essere molto più semplice se facciamo un presupposto alla matrice stringa di input:
public class Concatenation {
public static byte[] concatenate(String[] strs) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<strs.length; i++) {
sb.append(strs[i]);
if (i != strs.length-1) {
sb.append("*.*"); //concatenate by this splitter
}
}
return sb.toString().getBytes();
}
public static String[] split(byte[] bytes) {
String entire = new String(bytes);
return entire.split("\\*\\.\\*");
}
public static void main(String[] args) {
String[] input = {"This is","a serialization problem;","string concatenation will do as well","in some cases."};
byte[] byteArray = concatenate(input);
String[] output = split(byteArray);
for (String str: output) {
System.out.println(str);
}
}
}
Il presupposto è che *.*
non esiste in qualsiasi stringa dalla matrice di input. In altre parole, se si conosce in anticipo una sequenza speciale di simboli non apparirà in nessuna stringa dell'array di input, è possibile utilizzare quella sequenza come splitter.
fonte
2013-02-03 06:33:57
È possibile eseguire l'iterazione di ogni stringa e continuare ad aggiungersi alla matrice del byte finale. Esempio di frequenza = "Questo è un esempio"; // Converti stringa in byte [] usando la funzione .getBytes() byte [] bytes = example.getBytes(); // Converti byte [] in string usando una nuova stringa (byte []) String s = new String (byte); –
Hai visto questa domanda? http://stackoverflow.com/questions/1536054/how-to-convert-byte-array-to-string-and-vice-versa –
Ali B - Penso che la domanda che hai collegato risponda a una domanda leggermente diversa - specialmente quando vedi la risposta accettata, che giustamente fa notare che "se vuoi veramente memorizzare dati binari in un tipo String, dovresti usare la codifica Base64. – Floris