many many - 2 months ago 8
Java Question

converting files into different formats using single reusable code

i am a beginner in api programming. I am trying to write a reusable code for converting files from one format to any other formats.i am having an xml file and i would like to convert it into other file formats for instance to a .json or .csv files with a reusable code. I have created a java bean for that but I am not sure whether it helps me. I am kinda stuck how to start, any suggestions please. considering my xml file has all strings.

public class converter implements Serializable
{
public String name;
public String kind;
public String url;
public converter(){}
public converter(String name, String kind, String url){
getName(name);
getKind(kind);
getUrl(url);

}

private void getUrl(String url) {
// TODO Auto-generated method stub
this.url = url;
}
private void getKind(String kind) {
// TODO Auto-generated method stub
this.kind = kind;
}
private void getName(String name) {
// TODO Auto-generated method stub
this.name = name;
}


}

Answer

You can do something like a strategy pattern (or just search the web, tons of stuff on this one).

class Converter {
    ConversionAlgorithm algo;
    File file; // file to convert

    Converter(File file) {
        this.file = file;
    }

    void setConversionAlgorithm(ConversionAlgorithm algo) {
        this.algo = algo;
    }

    File convert() {
        return algo.convert(file);
    }
}

interface ConversionAlgorithm {
    File convert(File toConvert);
}

class JSONConverter implements ConversionAlgorithm {

    @Override
    File convert(File toConvert) {
        // do the conversion from xml to json
    }
}

class CSVConverter implements ConversionAlgorithm {

    @Override
    File convert(File toConvert) {
        // do the conversion from xml to csv
    }
}

So you create the converter with the file you want to operate on. Then you set the conversion algorithm according to the file type you want to get and call convert. If you want to convert to something else then just switch the conversion algorithm.

Usage example:

class Example {

    static ConversionAlgorithm xmlTojson = new JSONConverter();
    static ConversionAlgorithm xmlTocsv = new CSVConverter();

    public static void main(String[] args) {

        File xml = ... // get it somehow
        Converter converter = new Converter(xml);
        converter.setConversionAlgorithm(xmlTojson);
        File json = converter.convert();
        converter.setConversionAlgorithm(xmlTocsv);
        File csv = converter.convert();
    }
}

You can also choose to change the file with a setFile method. there are really a lot of ways to go about it.