【问题标题】:Convert DataHandler to string and also write content of datahandler into file将 DataHandler 转换为字符串并将 datahandler 的内容写入文件
【发布时间】:2014-11-17 03:47:57
【问题描述】:

我是网络服务的新手。我在 DataHandler 中收到来自客户端的响应。 我必须将数据处理程序的内容写入文件。我也想知道如何从数据处理程序中获取字符串中的数据。

我的程序是

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.";

    }

}

我在文件文件中得到 java.io.BufferedReader@28e70e30 而不是原始内容。 请帮帮我。

我的客户程序是

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);

    }

【问题讨论】:

    标签: java


    【解决方案1】:

    试试这个:

       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);
    

    【讨论】:

    • 有什么建议不需要包含 IOUtils 库吗?谢谢。
    猜你喜欢
    • 2014-11-10
    • 2011-02-19
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多