简体   繁体   中英

Store a list of Strings as human-readable path

I need to store a list of Strings into a single field in Java. The order is important, and I would prefer it to be stored in a human-readable format.

Perfect solution would be storing it like an xPath, but I only know libraries for compiling complex xml files to xPath, not lists of Strings.

My own written solutions easily get too complex because I want to support Strings containing any character, including the one I use as delimiter.

I currently use serialization this way:

String[] items = new String[3];
items[0] = item1;
items[1] = item2;
items[2] = item3;
byte[] bytes = SerializationUtils.serialize(items);
System.out.println("Serialized:\n"+Arrays.toString(bytes));

String[] read = (String[]) SerializationUtils.deserialize(bytes);
System.out.println("Read:");
for(String s : read) {
    System.out.println(s);
}

Output:

[-84, -19, 0, 5, 117, 114, 0, 19, 91, 76, 106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 83, 116, 114, 105, 110, 103, 59, -83, -46, 86, -25, -23, 29, 123, 71, 2, 0, 0, 120, 112, 0, 0, 0, 3, 116, 0, 7, 110, 117, 109, 98, 101, 114, 49, 116, 0, 8, 110, 117, 109, 98, 101, 114, 47, 50, 116, 0, 8, 110, 117, 109, 98, 101, 114, 92, 51]

This works, but apart from generating a very long String, it also generates a non-human readable string.

How can I best store this path, in a human readable way, and as little complication in my code as possible?

Solution

This is my solution using the OstermillerUtils as suggested by ct_ (thanks!).

String item1="number1";
String item2="number/2";
String item3="number\\3";
String item4="//number/4\\";
String item5=",num\"ber5,";
String item6="number,6";
String[] items = new String[6];
items[0] = item1;
items[1] = item2;
items[2] = item3;
items[3] = item4;
items[4] = item5;
items[5] = item6;

    System.out.println("Test values");
for(String s : items) {
    System.out.println(s);
}

StringWriter writer = new StringWriter();
CSVPrinter printer = new CSVPrinter(writer);
printer.changeDelimiter('/');
printer.write(items);
System.out.println("Persisted:\n\t"+writer.toString());

String[][] results = CSVParser.parse(writer.toString(), '/');
for (int j=0; j<results[0].length; j++){
    System.out.println(results[0][j]);
}

So you want to serialize and deserialize a String array to a string and back? Have a look at http://ostermiller.org/utils/CSV.html - it can serialize and deserialize arrays using an arbitrary delimeter.

JAXB only using annotations would work. Best when you have one container class with a list field. You then get XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM