幽州1
我建議你serialize Array to Base64:
public String serializeArray(final String[] data) {
try (final ByteArrayOutputStream boas = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream(boas)) {
oos.writeObject(data);
return Base64.getEncoder().encodeToString(boas.toByteArray());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
然後反序列中的Base64到一個數組:
public String[] deserializeArray(final String data) {
try (final ByteArrayInputStream bias = new ByteArrayInputStream(Base64.getDecoder().decode(data));
final ObjectInputStream ois = new ObjectInputStream(bias)) {
return (String[]) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
這需要Java 8.
實施例:
public static void main(String args[]) throws Exception {
String[] stringArray = new String[]{"One,", "Two", "Three"};
String serialized = serializeArray(stringArray);
String[] deserialized = deserializeArray(serialized);
System.out.println(Arrays.toString(stringArray));
System.out.println(serialized);
System.out.println(Arrays.toString(deserialized));
}
輸出
[One,, Two, Three]
rO0ABXVyABNbTGphdmEubGFuZy5TdHJpbmc7rdJW5+kde0cCAAB4cAAAAAN0AARPbmUsdAADVHdvdAAFVGhyZWU=
[One,, Two, Three]
注意,這適用於任何Object
即implements Serializable
,而不僅僅是String[]
。
舉一個簡單的選擇,你可以通過\,
加入陣列之前更換,
,然後還,
分裂後把它放回\,
。這依賴於CSV使用的標準「轉義分隔符」模式。但是如果用戶在輸入的某個地方輸入\,
,那麼它會失敗,因此不太健壯:YMMV。
public String serializeArray(final String[] data) {
return Arrays.stream(data)
.map(s -> s.replace(",", "\\,"))
.collect(joining(","));
}
public String[] deserializeArray(final String data) {
return Pattern.compile("(?<!\\\\),").splitAsStream(data)
.map(s -> s.replace("\\,", ","))
.toArray(String[]::new);
}
你不能。除非你有**規則**。什麼是規則? –
從字符串[]轉換爲字符串並從字符串轉換回字符串[]必須是冪等運算 – alexanoid
爲什麼多餘的轉換? – shmosel