Java 我想将输出流转换为 String 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2472155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:08:35  来源:igfitidea点击:

I want to convert an output stream into String object

javajaxb

提问by TopCoder

I want to convert an OutputStreaminto a Stringobject. I am having an OutputStreamobject returned after marshalling the JAXB object.

我想将 an 转换OutputStream为一个String对象。我OutputStream在编组 JAXB 对象后返回了一个对象。

采纳答案by Justin Gregtheitroade

not very familiar with jaxb, from what i was able to find you can convert into a string using

对 jaxb 不是很熟悉,根据我能找到的内容,您可以使用以下方法将其转换为字符串

public String asString(JAXBContext pContext, 
                        Object pObject)
                            throws 
                                JAXBException {

    java.io.StringWriter sw = new StringWriter();

    Marshaller marshaller = pContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.marshal(pObject, sw);

    return sw.toString();
}

ws.apache.org

ws.apache.org

but I'm not sure about a stirng object. still searching.

但我不确定一个搅动的物体。仍在搜索中。

** EDIT

** 编辑

Marshalling a non-element

Another common use case is where you have an object that doesn't have @XmlRootElement on it. JAXB allows you to marshal it like this:

marshaller.marshal( new JAXBElement(
new QName("","rootTag"),Point.class,new Point(...)));

This puts the element as the root element, followed by the contents of the object, then . You can actually use it with a class that has @XmlRootElement, and that simply renames the root element name.

At the first glance the second Point.class parameter may look redundant, but it's actually necessary to determine if the marshaller will produce (infamous) @xsi:type. In this example, both the class and the instance are Point, so you won't see @xsi:type. But if they are different, you'll see it.

This can be also used to marshal a simple object, like String or an integer.

marshaller.marshal( new JAXBElement(
new QName("","rootTag"),String.class,"foo bar"));

But unfortunately it cannot be used to marshal objects like List or Map, as they aren't handled as the first-class citizen in the JAXB world.

编组一个非元素

另一个常见用例是您的对象上没有 @XmlRootElement。JAXB 允许您像这样编组它:

marshaller.marshal(new JAXBElement(
new QName("","rootTag"),Point.class,new Point(...)));

这会将元素作为根元素,然后是对象的内容,然后是 。您实际上可以将它与具有@XmlRootElement 的类一起使用,并且只需重命名根元素名称。

乍一看,第二个 Point.class 参数可能看起来多余,但实际上有必要确定编组器是否会生成(臭名昭著的)@xsi:type。在这个例子中,类和实例都是 Point,所以你不会看到 @xsi:type。但如果它们不同,你就会看到。

这也可用于封送简单对象,如字符串或整数。

marshaller.marshal(new JAXBElement(
new QName("","rootTag"),String.class,"foo bar"));

但不幸的是,它不能用于编组 List 或 Map 之类的对象,因为它们在 JAXB 世界中不被视为一等公民。

found HERE

这里找到

回答by Stevie754

public String readFile(String pathname) throws IOException {
    File file = new File(pathname);
    StringBuilder fileContents = new StringBuilder((int) file.length());
    Scanner scanner = new Scanner(file);
    String lineSeparator = System.getProperty("line.separator");

    try {
        while (scanner.hasNextLine()) {
            fileContents.append(scanner.nextLine() + lineSeparator);
        }
        return fileContents.toString();
    }
    finally {
        scanner.close();
    }
}    

Method to handle the XML and convert it to a string.

处理 XML 并将其转换为字符串的方法。

JAXBContext jc = JAXBContext.newInstance(ClassMatchingStartofXMLTags.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    //store filepath to be used
    String filePath = "YourXMLFile.xml";
    File xmlFile = new File(filePath);
    //Set up xml Marshaller
    ClassMatchingStartofXMLTags xmlMarshaller = (ClassMatchingStartofXMLTags) unmarshaller.unmarshal(xmlFileEdit);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    // Use marshall to output the contents of the xml file
    System.out.println("Marshalled XML\n");
    marshaller.marshal(xmlMarshaller, System.out); 
    //Use Readfile method to convert the XML to a string and output the results
    System.out.println("\nXML to String");
    String strFile = ReadFile(xmlFile)
    System.out.println(strFile);     

Method within your class to get the XML and Marshall it EditThe above method will both output the marshalled xml and also the xml as a string.

类中获取 XML 并对其 进行编组的方法Edit上述方法将输出编组的 xml 和 xml 作为字符串。

回答by Rodrigo Valentim

    StringWriter sw = new StringWriter();
    com.integra.xml.Integracao integracao = new Integracao();
    integracao.add(...);
try {
    JAXBContext context = JAXBContext.newInstance("com.integra.xml");
    Marshaller marshaller = context.createMarshaller();
    marshaller.marshal(integracao, sw );
    System.out.println(sw.toString());
} catch (JAXBException e) {
    e.printStackTrace();
}

回答by Rajesh B

Yes, there is a way to do it: just pass the String writer as input to it. So that it the xml created will be written to it

是的,有一种方法可以做到:只需将 String writer 作为输入传递给它。以便将创建的 xml 写入其中

   public void saveSettings() throws IOException {
       FileOutputStream os = null;
       //Declare a StringWriter to which the output has to go
       StringWriter sw = new StringWriter();
       try {
           Answer ans1=new Answer(101,"java is a programming language","ravi");  
           Answer ans2=new Answer(102,"java is a platform","john");  

           ArrayList<Answer> list=new ArrayList<Answer>();  
           list.add(ans1);  
           list.add(ans2);  

           settings=new Question(1,"What is java?",list); 
           os = new FileOutputStream(FILE_NAME);
           this.marshaller.marshal(settings, new StreamResult(sw));
           System.out.println(sw.toString());
           new File(FILE_NAME).delete();
       } finally {
           if (os != null) {
               os.close();
           }
       }
   }