是否可以将 OutStream 转换为字符串?

Is it possible to convert OutStream to a string?

我有一个使用 DOM 解析来构建 XML 文件的方法,它需要一个 OutputStream 作为参数。我正在尝试从命令行 运行 程序,但命令行选项只接受字符串。

我可以 运行 通过输入 System.out 作为参数并 运行 运行程序,但仅此而已。

这是一段代码:

public class WriteSourceTranslatedToTXML extends GetSourceSentences {

    public static String makeTranslated(OutputStream output, String out) throws ParserConfigurationException, IOException, SAXException, URISyntaxException {

        System.out.println("---creating XML file---");
        Document doc = new Document();
        doc.setRootElement(new Element("txml"));

        // Built XML here and inserted sentences
        xmlOutputter.setFormat(Format.getPrettyFormat());
        xmlOutputter.output(doc, output);

        // Write to file
        XMLOutputter xout = new XMLOutputter();
        String xml = xout.outputString(doc.getRootElement().getContent());

        try(FileOutputStream fileOutputStream =
               new FileOutputStream(out)) {
                   xmlOutputter.output(doc, fileOutputStream);

这里是命令行代码:

@Command(name = "fileCli", description = "Performs file manipulation operations", mixinStandardHelpOptions = true, version = "File Client 1.0")

public class TranslateTXML implements Callable<String> {

    @Option(names = "-o", description = "output path")
    private String output;
    if (output != null) {
        WriteSourceTranslatedToTXML.makeTranslated(output); // Red line under output
        System.out.println("translated made");
        System.out.println("------");
        System.out.println("File \"translated.txml\" has been outputted to designated path");

我该怎么做?

我使用了另一种方法 Java 构建 XML 文件。

新方法调用不需要 OutputStream 参数,只需要一个字符串,我将其设置为文件路径。

public static void createXml(String directory) throws IOException, TransformerException, ParserConfigurationException {

    BufferedReader sourceReader = new BufferedReader(new FileReader(db));

    .
    .

    // Use DocumentBuilder and construct the XML file using NodeList Collection
    .
    .

    DOMSource source = new DOMSource(doc);

    // Write to console or file
    StreamResult console = new StreamResult(System.out);
    StreamResult file = new StreamResult(new File(directory));
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    // For pretty print
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // Write data
    transformer.transform(source, console);
    transformer.transform(source, file);
    sourceReader.close();

因此,通过使用 DOM 解析器、Transformer 和 StreamResult,我可以构建 .xml 文件并将其存储在带有 StreamResult 的 Stream 中(输出需要一个 String 参数)。 瞧!