2

I created xml file using java. I just want to copy the xml file which was there in console to notepad through coding not through run configuration process...... I tried using

PrintStream out = new PrintStream(new FileOutputStream("notepad.txt"));
System.setOut(out);

But the above line results in creation of notepad in particular location. But data is not copied inside the notepad. It results in empty notepad.

For creating xml: I used this below code which works fine

Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.METHOD, "xml");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");         Source src = new DOMSource(xmlDoc); Result dest = new StreamResult(System.out);
tf.transform(src, dest);

Anyone please help me on this....

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
kumar
  • 33
  • 3
  • By "notepad" do you mean the Windows text editor Notepad? Do you want a new Notepad window to open with your xml in it? Or do you want the XML to appear in an existing Notepad window? Is it OK if a new file is created, or is it important that Notepad contains an unsaved buffer? – slim Jun 12 '17 at 12:29
  • Did you try `out.flush();` or `out.close();` at the end? – eztam Jun 12 '17 at 12:30
  • i want to save in new notepad file mate.. –  kumar Jun 12 '17 at 12:36
  • I didnt use that out.flush(); –  kumar Jun 12 '17 at 12:36
  • May be duplicate of https://stackoverflow.com/questions/1994255/how-to-write-console-output-to-a-txt-file – Sanjay Jun 12 '17 at 12:38

1 Answers1

1

It looks like you are using StreamResult class, so let's have a look at the constructor:

public StreamResult(OutputStream outputStream)

Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.

So, it acccepts the OutputStream as an argument, so you can either pass out or new FileOutputStream("notepad.txt") while creating an instance of StreamResult e,g.:

Result dest = new StreamResult(out);
out.close();

OR

OutputStream fileOutputStream = new FileOutputStream("notepad.txt");
Result dest = new StreamResult(fileOutputStream);
fileOutputStream.close();

This would make sure the content gets written into the file. There is no need to use System.out for this.

Update

In order to print the same content to console, you will have to do another transformation with StringWriter, e.g.:

StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
tf.transform(src, result);
System.out.println(result.toString());

This would print the content into console.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102