Convert DataHandler to string and also write data handler content to file

I am new to webservice. I am getting a response from the client in the DataHandler. I have to write the content of the data handler to a file. And also I want to know how to get data in string from data handler.

My program

package com.ws.mtom;

import java.io.File;
import java.io.FileOutputStream;

import javax.activation.DataHandler;
import javax.jws.WebService;

@WebService(endpointInterface = "com.ws.mtom.WSInterface")
public class WSImpl implements WSInterface {

    @Override
    public String writeFile(DataHandler sTr) {
        try {
            File file = new File("D:\\xml\\efg.xml");
            file.createNewFile();
            FileOutputStream fop = new FileOutputStream(file);    
            sTr.writeTo(fop);           
        } catch (Exception e) {
            return "Fail to write content in file";
        }
        return "Chutiyap hogaya hai.";

    }

}

      

I am getting java.io.BufferedReader@28e70e30 in the file file and not the original one. please help me.

my client program

public static void main(String[] args) throws Exception {
        URL wsdlUrl = new URL("http://localhost:8087/ws/fileHandling/?wsdl");
        QName qname = new QName("http://mtom.ws.com/", "WSImplService");
        Service service = Service.create(wsdlUrl, qname);
        DataSource ds = new ByteArrayDataSource(getFileContentAsString("D:\\xml\\abc.xml").getBytes(), "text/plain; charset=UTF-8");
        DataHandler handler = new DataHandler(ds);
        WSInterface intr = service.getPort(WSInterface.class);
        String str = intr.writeFile(handler);

    }

      

+3


source to share


1 answer


Try the following:



   FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    //convert your DataHandler to String
    String stringToWrite = IOUtils.toString(sTr.getInputStream, "UTF-8");
    //Write String to file
    bw.write(stringToWrite);

      

+1


source







All Articles