views:

5205

answers:

7

I need to be able to serialize a string and then have it save in a .txt or .xml file. I've never used the implementation to read/write files, just remember I am a relative beginner. Also, I need to know how to deserialize the string to be printed out in terminal as a normal string.

A: 

Is there any particular reason to use XStream? This would be extremely easy to do with something like JDOM if all you are doing is trying to serialize a string or two.

Ie, something like: Document doc = new Document();

Element rootEl = new Element("root");
rootEl.setText("my string");
doc.appendChild(rootEl);
XMLOutputter outputter = new XMLOutputter();
outputter.output(doc);

Some of the details above are probably wrong, but thats the basic flow. Perhaps you should ask a more specific question so that we can understand exactly what problem it is that you are having?

jsight
A: 

From http://www.xml.com/pub/a/2004/08/18/xstream.html:

import com.thoughtworks.xstream.XStream;

class Date {
    int year;
    int month;
    int day;
}

public class Serialize {
    public static void main(String[] args) {

        XStream xstream = new XStream();

        Date date = new Date();
        date.year = 2004;
        date.month = 8;
        date.day = 15;

        xstream.alias("date", Date.class);

        String decl = "\n";

        String xml = xstream.toXML(date);

        System.out.print(decl + xml);
    }
}

public class Deserialize {

    public static void main(String[] args) {

        XStream xstream = new XStream();

        Date date = new Date();

        xstream.alias("date", Date.class);

        String xml = xstream.toXML(date);

        System.out.print(xml);

        Date newdate = (Date)xstream.fromXML(xml);
        newdate.month = 12;
        newdate.day = 2;

        String newxml = xstream.toXML(newdate);

        System.out.print("\n\n" + newxml);
    }
}

You can then take the xml string and write it to a file.

Alex Beardsley
+3  A: 

If you can serialize it to a txt file, just open an ObjectOutputStream and have it use String's own serialization capability for you.

String str = "serialize me";
 String file = "file.txt";
 try{
  ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
  out.writeObject(str);
  out.close();

  ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
  String newString = (String) in.readObject();
  assert str.equals(newString);
  System.out.println("Strings are equal");
 }catch(IOException ex){
  ex.printStackTrace();
 }catch(ClassNotFoundException ex){
  ex.printStackTrace();
 }

You could also just open a PrintStream and syphon it out that way, then use a BufferedReader and readLine(). If you really want to get fancy (since this is a HW assignment after all), you could use a for loop and print each character individually. Using XML is more complicated than you need to serialize a String and using an external library is just overkill.

James
+1  A: 

XStream has facilities to read from and write to files, see the simple examples (Writer.java and Reader.java) in this article:

http://www.ibm.com/developerworks/library/x-xstream/index.html

+1  A: 

If you need to create a text file containing XML that represents the contents of an object (and make it bidirectional), just use JSON-lib:

class MyBean{  
   private String name = "json";  
   private int pojoId = 1;  
   private char[] options = new char[]{'a','f'};  
   private String func1 = "function(i){ return this.options[i]; }";  
   private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");  

   // getters & setters  
   ...  
}  

JSONObject jsonObject = JSONObject.fromObject( new MyBean() );
String xmlText = XMLSerializer.write( jsonObject );

From there just wrote the String to your file. Much simpler than all those XML API's. Now, however, if you need to conform to a DTD or XSD, this is a bad way to go as it's much more free-format and conforms only to the object layout.

http://json-lib.sourceforge.net/usage.html

Piko

Piko
+2  A: 

If you are beginning Java, then take some time to look through the Apache Commons project. There are lots of basic extensions to java that you will make use of many times.

I'm assuming you just want to persist a string so you can read it back later - in which case it doesn't necessarily need to be XML.

To write a string to a file, see org.apache.commons.io.FileUtils:

FileUtils.writeStringToFile(File file,String data)

To read it back:

FileUtils.readFileToString(File file)

References:

http://commons.apache.org/

http://commons.apache.org/io

http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html

Make sure you also look at commons-lang for lots of good basic stuff.

prule
A: 

try something like this:

    FileOutputStream fos = null;
    try {
        new File(FILE_LOCATION_DIRECTORY).mkdirs();
        File fileLocation = new File(FILE_LOCATION_DIRECTORY + "/" + fileName);
        fos = new FileOutputStream(fileLocation);
        stream.toXML(userAlertSubscription, fos);                
    } catch (IOException e) {
        Log.error(this, "Error %s in file %s", e.getMessage(), fileName);
    } finally {
        IOUtils.closeQuietly(fos);
    }
yeforriak